-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.java
More file actions
68 lines (64 loc) · 2.37 KB
/
Copy pathNQueen.java
File metadata and controls
68 lines (64 loc) · 2.37 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
import java.util.Scanner;
public class NQueen {
static int n;
static int solutions;
public static void main(String[] args) {
System.out.println("有几个皇后?");
Scanner scanner = new Scanner(System.in);
n = Integer.parseInt(scanner.nextLine());
scanner.close();
Boolean[][] chessPlate = new Boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
chessPlate[i][j] = false;
}
}
solutions = 0;
Step(chessPlate, 0);
System.out.println(solutions);
}
static void Step(Boolean[][] chessPlate, int currentRow) {
for (int currentColumn = 0; currentColumn < n; currentColumn++) {
if (!chessPlate[currentRow][currentColumn]) {
Boolean[][] newPlate = new Boolean[n][n];
for (int i = 0; i < n; i++) {
newPlate[i] = chessPlate[i].clone();
}
if (currentRow == n - 1) {
solutions++;
} else {
Step(MarkQueenAttacks(newPlate, currentRow, currentColumn), currentRow + 1);
}
}
}
}
static Boolean[][] MarkQueenAttacks(Boolean[][] chessPlate, int x, int y) {
for (int i = 0; i < chessPlate.length; i++) {
chessPlate[x][i] = true;
}
for (int i = 0; i < chessPlate[0].length; i++) {
chessPlate[i][y] = true;
}
for (int[] position = { x, y }; position[0] < chessPlate.length && position[1] < chessPlate[0].length;) {
chessPlate[position[0]][position[1]] = true;
position[0]++;
position[1]++;
}
for (int[] position = { x, y }; position[0] >= 0 && position[1] < chessPlate[0].length;) {
chessPlate[position[0]][position[1]] = true;
position[0]--;
position[1]++;
}
for (int[] position = { x, y }; position[0] < chessPlate.length && position[1] >= 0;) {
chessPlate[position[0]][position[1]] = true;
position[0]++;
position[1]--;
}
for (int[] position = { x, y }; position[0] >= 0 && position[1] >= 0;) {
chessPlate[position[0]][position[1]] = true;
position[0]--;
position[1]--;
}
return chessPlate;
}
}