-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueensII.java
More file actions
47 lines (41 loc) · 1.3 KB
/
Copy pathNQueensII.java
File metadata and controls
47 lines (41 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Follow up for N-Queens problem.
* Now, instead outputting board configurations, return the total number of distinct solutions.
*
* @author joshluo
*
*/
public class NQueensII {
int result = 0;
public int totalNQueens(int n) {
assert (n > 0);
int[] colByRow = new int[n];
totalNQueensDFS(colByRow, 0, n);
return result;
}
private void totalNQueensDFS(int[] colByRow, int currentRow, int boardSize) {
if (currentRow == boardSize) {
result++;
} else {
for (int col = 0; col < boardSize; col++) {
colByRow[currentRow] = col;
if (validPosition(colByRow, currentRow)) {
totalNQueensDFS(colByRow, currentRow + 1, boardSize);
}
}
}
}
private boolean validPosition(int[] colByRow, int currentRow) {
for (int row = 0; row < currentRow; row++) {
if (colByRow[row] == colByRow[currentRow]
|| Math.abs(colByRow[row] - colByRow[currentRow]) == currentRow - row) {
return false;
}
}
return true;
}
public static void main(String args[]) {
NQueensII solution = new NQueensII();
System.out.println(solution.totalNQueens(1));
}
}