-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnQueens.java
More file actions
75 lines (73 loc) · 2.56 KB
/
nQueens.java
File metadata and controls
75 lines (73 loc) · 2.56 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.*;
public class nQueens {
/*
don't need to actually place the queen,
instead, for each row, try to place without violation on
col/ diagonal1/ diagnol2.
trick: to detect whether 2 positions sit on the same diagnol:
if delta(col, row) equals, same diagnol1;
if sum(col, row) equals, same diagnal2.
*/
public static void main(String[] args){
nQueens obj = new nQueens();
System.out.println(obj.totalNQueens(4));
System.out.println(obj.pathNQueens(4));
}
int count;
public int totalNQueens(int n){
count =0;
Set<Integer> cols = new HashSet<>();
Set<Integer> dia1s = new HashSet<>();
Set<Integer> dia2s = new HashSet<>();
countHelper(0, n, cols, dia1s, dia2s);
return count;
}
private void countHelper(int row, int n, Set<Integer> cols, Set<Integer> dia1s, Set<Integer>dia2s){
if(row == n){
count ++;
return;
}
for(int col=0; col < n; col++){
if(cols.contains(col) || dia1s.contains(col-row) || dia2s.contains(col+row)){
continue;
}
System.out.println(Arrays.toString(new int[] {row,col}));
cols.add(col);
dia1s.add(col-row);
dia2s.add(col+row);
countHelper(row+1,n,cols,dia1s,dia2s);
cols.remove(col);
dia1s.remove(col-row);
dia2s.remove(col+row);
}
}
public List<List<Integer>> pathNQueens(int n){
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Set<Integer> cols = new HashSet<>();
Set<Integer> dia1s = new HashSet<>();
Set<Integer> dia2s = new HashSet<>();
pathHelper(0,n,path, res, cols, dia1s, dia2s);
return res;
}
private void pathHelper(int row, int n, List<Integer> path, List<List<Integer>> res, Set<Integer> cols, Set<Integer> dia1s, Set<Integer>dia2s){
if(row == n){
res.add(new ArrayList<>(path));
return;
}
for(int col=0; col < n; col++){
if(cols.contains(col) || dia1s.contains(col-row) || dia2s.contains(col+row)){
continue;
}
cols.add(col);
dia1s.add(col-row);
dia2s.add(col+row);
path.add(col);
pathHelper(row+1, n, path, res, cols, dia1s, dia2s);
cols.remove(col);
dia1s.remove(col-row);
dia2s.remove(col+row);
path.remove(path.size()-1);
}
}
}