Skip to content

Commit cc6bf38

Browse files
committed
eight queens
1 parent c5c10af commit cc6bf38

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package backtracking;
2+
3+
public class EightQueens {
4+
5+
public static void main(String[] args) {
6+
EightQueens obj = new EightQueens();
7+
obj.cal8queens(0);
8+
}
9+
10+
int count = 0;
11+
int[] result = new int[8];//全局或成员变量,下标表示行,值表示queen存储在哪一列
12+
public void cal8queens(int row) { // 调用方式:cal8queens(0);
13+
if (row == 8) { // 8个棋子都放置好了,打印结果
14+
printQueens(result);
15+
return; // 8行棋子都放好了,已经没法再往下递归了,所以就return
16+
}
17+
for (int column = 0; column < 8; ++column) { // 每一行都有8中放法
18+
if (isOk(row, column)) { // 有些放法不满足要求
19+
result[row] = column; // 第row行的棋子放到了column列
20+
cal8queens(row+1); // 考察下一行
21+
}
22+
}
23+
}
24+
25+
private boolean isOk(int row, int column) {//判断row行column列放置是否合适
26+
int leftup = column - 1, rightup = column + 1;
27+
for (int i = row-1; i >= 0; --i) { // 逐行往上考察每一行
28+
if (result[i] == column) return false; // 第i行的column列有棋子吗?
29+
if (leftup >= 0) { // 考察左上对角线:第i行leftup列有棋子吗?
30+
if (result[i] == leftup) return false;
31+
}
32+
if (rightup < 8) { // 考察右上对角线:第i行rightup列有棋子吗?
33+
if (result[i] == rightup) return false;
34+
}
35+
--leftup; ++rightup;
36+
}
37+
return true;
38+
}
39+
40+
private void printQueens(int[] result) { // 打印出一个二维矩阵
41+
System.out.println(">>>>>> solution " + (++count) + " <<<<<<<<");
42+
for (int row = 0; row < 8; ++row) {
43+
for (int column = 0; column < 8; ++column) {
44+
if (result[row] == column) System.out.print("Q ");
45+
else System.out.print("* ");
46+
}
47+
System.out.println();
48+
}
49+
System.out.println();
50+
}
51+
}

0 commit comments

Comments
 (0)