-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNQueens.java
60 lines (54 loc) · 1.58 KB
/
NQueens.java
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by cpacm on 2017/6/24.
*/
public class NQueens {
private static List<List<String>> resultList = new ArrayList<>();
private static int[] positions;
private static char[] tags;
public static void main(String[] args) {
System.out.println(solveNQueens(8));
}
public static List<List<String>> solveNQueens(int n) {
positions = new int[n];
tags = new char[n];
Arrays.fill(positions, -1);
Arrays.fill(tags, '.');
dp(0, n);
return resultList;
}
public static void dp(int n, int max) {
if (n == max) {
List<String> qLine = new ArrayList<>();
for (int i = 0; i < positions.length; i++) {
tags[positions[i]] = 'Q';
String q = new String(tags);
qLine.add(q);
tags[positions[i]] = '.';
}
resultList.add(qLine);
return;
}
int valueX = n;
int valueY = 0;
while (valueY < max) {
if (hasPlaced(n, valueX, valueY)) {
positions[n] = valueY;
dp(n + 1, max);
}
valueY++;
}
}
public static boolean hasPlaced(int n, int valueX, int valueY) {
for (int j = 0; j < n; j++) {
int x = j;
int y = positions[j];
if (positions[j] == valueY || Math.abs(valueX - x) == Math.abs(valueY - y)) {
return false;
}
}
return true;
}
}