Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | |

<br/>
<div align="right">
Expand Down
61 changes: 61 additions & 0 deletions dart/n_queens.dart
Original file line number Diff line number Diff line change
@@ -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<List<String>> solveNQueens(int n) {
final List<List<String>> board = List.generate(n, (_) => List<String>.filled(n, '.'));
final List<List<String>> ans = [];
backtrack(board, ans, 0, 0, n);
return ans;
}

bool isSafe(List<List<String>> 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<List<String>> board, List<List<String>> 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<String> convert(List<List<String>> board) {
final List<String> ans = [];
for (int i = 0; i < board.length; i++) {
final row = board[i].join('');
ans.add(row);
}

return ans;
}
}