public class EightQueens {
final int N = 8;
int[] cols = new int[N];
public void placeQueens() {
if (solve(0)) {
displayBoard();
} else {
System.out.println("不存在解决方案");
}
}
public boolean solve(int row) {
if (row == N) {
return true;
}
for (int col = 0; col < N; col++) {
cols[row] = col;
if (isValid(row)) {
if (solve(row + 1)) {
return true;
}
}
}
return false;
}
public boolean isValid(int row) {
for (int i = 0; i < row; i++) {
if (cols[i] == cols[row] || Math.abs(cols[i] - cols[row]) == row - i) {
return false;
}
}
return true;
}
public void displayBoard() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (cols[i] == j) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
EightQueens eightQueens = new EightQueens();
eightQueens.placeQueens();
}
}
八皇后问题(JAVA版)
最新推荐文章于 2024-08-30 18:40:43 发布