diff --git a/README.md b/README.md index 85accc7..0280fac 100644 --- a/README.md +++ b/README.md @@ -375,6 +375,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 980 | [Unique Paths III](https://leetcode.com/problems/unique-paths-iii/) | [C++](./C++/Unique-Paths-III.cpp) | _O(R * C * 2 ^ (R \* C))_ | _O(R \* C)_ | Hard | DFS, Memoization | | | 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/) | [C++](./C++/combination-sum.cpp) | _O(2^n)_ | _O(n)_ | Medium | Array, Backtracking | | | 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) | [C++](./C++/letter-combinations-of-a-phone-number.cpp) | _O(4^n)_ | _O(n)_ | Medium | String, Hash Table, Backtracking | | +| 051 | [N Queens](https://leetcode.com/problems/n-queens/description/) | [Dart](./dart/n_queens.dart) | _O(n!)_ | _O(n)_ | Hard | Array, Backtracking | |
diff --git a/dart/n_queens.dart b/dart/n_queens.dart new file mode 100644 index 0000000..45aa130 --- /dev/null +++ b/dart/n_queens.dart @@ -0,0 +1,61 @@ +/* +The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. + +Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. +*/ + +class Solution { + List> solveNQueens(int n) { + final List> board = List.generate(n, (_) => List.filled(n, '.')); + final List> ans = []; + backtrack(board, ans, 0, 0, n); + return ans; + } + + bool isSafe(List> board, int row, int col) { + for (int i = 0; i < row; i++) { + if (board[i][col] == 'Q') { + return false; + } + } + + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + if (board[i][j] == 'Q') { + return false; + } + } + + for (int i = row, j = col; i >= 0 && j < board.length; i--, j++) { + if (board[i][j] == 'Q') { + return false; + } + } + + return true; + } + + void backtrack(List> board, List> ans, int row, int col, int queens) { + if (row == queens) { + ans.add(convert(board)); + return; + } + + for (int col = 0; col < board.length; col++) { + if (isSafe(board, row, col)) { + board[row][col] = 'Q'; + backtrack(board, ans, row + 1, col, queens); + board[row][col] = '.'; + } + } + } + + List convert(List> board) { + final List ans = []; + for (int i = 0; i < board.length; i++) { + final row = board[i].join(''); + ans.add(row); + } + + return ans; + } +} \ No newline at end of file