Skip to content

Commit e92ba70

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 52_N-Queens_II.java
1 parent 413b1f7 commit e92ba70

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Backtracking/52_N-Queens_II.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public int totalNQueens(int n) {
3+
if (n == 0) {
4+
return 0;
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+
int[] result = new int[1];
15+
dfs(board, 0, result);
16+
return result[0];
17+
}
18+
19+
private boolean isValid(char[][] board, int row, int col) {
20+
for (int i = 0; i < board.length; i++) {
21+
for (int j = 0; j < board[i].length; j++) {
22+
if (board[i][j] == 'Q' && (row == i || row + j == col + i || row + col == i + j)) {
23+
return false;
24+
}
25+
}
26+
}
27+
28+
return true;
29+
}
30+
31+
private void dfs(char[][] board, int colIdx, int[] result) {
32+
if (colIdx == board.length) {
33+
++result[0];
34+
return;
35+
}
36+
37+
for (int i = 0; i < board.length; i++) {
38+
if (isValid(board, i, colIdx)) {
39+
board[i][colIdx] = 'Q';
40+
dfs(board, colIdx + 1, result);
41+
board[i][colIdx] = '.';
42+
}
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)