-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathNQueens2.java
More file actions
47 lines (36 loc) · 1.2 KB
/
NQueens2.java
File metadata and controls
47 lines (36 loc) · 1.2 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
package Algorithms;
import java.util.ArrayList;
public class NQueens2 {
public static void main(String[] args) {
NQueens2 nq = new NQueens2();
nq.totalNQueens(1);
}
public int totalNQueens(int n) {
ArrayList<Integer> cols = new ArrayList<Integer>();
return totalNQueensHelp(n, cols, 0);
}
public boolean isValid(ArrayList<Integer> cols, int col) {
for (int i = 0; i < cols.size(); i++) {
if (col == cols.get(i) || (cols.size() - i == Math.abs(col - cols.get(i)))) {
return false;
}
}
return true;
}
public int totalNQueensHelp(int n, ArrayList<Integer> cols, int total) {
if (cols.size() == n) {
// get a new solution.
return total + 1;
}
int newTotal = total;
for (int i = 0; i < cols.size(); i ++) {
if (!isValid(cols, i)) { // this is not a solution.
continue;
}
cols.add(i);
newTotal = totalNQueensHelp(n, cols, newTotal);
cols.remove(cols.size() - 1);
}
return newTotal;
}
}