Skip to content

Commit 413b1f7

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 51_N-Queens.java
1 parent 297c0b1 commit 413b1f7

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Backtracking/51_N-Queens.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Solution {
2+
public List<List<String>> solveNQueens(int n) {
3+
if (n == 0) {
4+
return Collections.emptyList();
5+
}
6+
7+
char[][] board = new char[n][n];
8+
for (int i = 0; i < n; i++) {
9+
for (int j = 0; j < n; j++) {
10+
board[i][j] = '.';
11+
}
12+
}
13+
14+
List<List<String>> result = new ArrayList<>();
15+
dfs(board, 0, result);
16+
return result;
17+
}
18+
19+
private List<String> constructBoard(char[][] board) {
20+
List<String> result = new ArrayList<>();
21+
22+
for (int i = 0; i < board.length; i++) {
23+
String row = new String(board[i]);
24+
result.add(row);
25+
}
26+
27+
return result;
28+
}
29+
30+
private boolean isValid(char[][] board, int row, int col) {
31+
for (int i = 0; i < board.length; i++) {
32+
for (int j = 0; j < board[i].length; j++) {
33+
if (board[i][j] == 'Q' && (row == i || row + j == col + i || row + col == i + j)) {
34+
return false;
35+
}
36+
}
37+
}
38+
39+
return true;
40+
}
41+
42+
private void dfs(char[][] board, int colIdx, List<List<String>> result) {
43+
if (colIdx == board.length) {
44+
result.add(constructBoard(board));
45+
return;
46+
}
47+
48+
for (int i = 0; i < board.length; i++) {
49+
if (isValid(board, i, colIdx)) {
50+
board[i][colIdx] = 'Q';
51+
dfs(board, colIdx + 1, result);
52+
board[i][colIdx] = '.';
53+
}
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)