写一个八皇后小游戏的Java代码
时间: 2024-01-29 19:02:20 浏览: 58
自己写的java八皇后小游戏源代码
5星 · 资源好评率100%
当然可以,下面是八皇后小游戏的Java代码:
```java
public class EightQueens {
private int row = 8;
private int[] result = new int[row];
private int count = 0;
public void getEightQueens() {
check(0);
System.out.println("共有" + count + "种解法!");
}
private void check(int n) {
if (n == row) {
printQueens();
count++;
return;
}
for (int i = 0; i < row; i++) {
result[n] = i;
if (judge(n)) {
check(n + 1);
}
}
}
private boolean judge(int n) {
for (int i = 0; i < n; i++) {
if (result[i] == result[n] || Math.abs(n - i) == Math.abs(result[n] - result[i])) {
return false;
}
}
return true;
}
private void printQueens() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
if (result[i] == j) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
EightQueens eightQueens = new EightQueens();
eightQueens.getEightQueens();
}
}
```
有什么问题需要我帮您解答么?
阅读全文