N皇后问题 Java 代码实现 | 回溯算法详解
public class NQueen {
private int n; // 棋盘大小
private int[] board; // 存储每一行中皇后的位置
public NQueen(int n) {
this.n = n;
board = new int[n];
}
// 判断当前位置是否合法
private boolean isValid(int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i] == col || Math.abs(row - i) == Math.abs(col - board[i])) {
return false;
}
}
return true;
}
// 回溯法求解N皇后问题
private void backtrack(int row) {
if (row == n) {
printBoard();
return;
}
for (int i = 0; i < n; i++) {
if (isValid(row, i)) {
board[row] = i;
backtrack(row + 1);
}
}
}
// 打印棋盘
private void printBoard() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i] == j) {
System.out.print('Q' + ' ');
} else {
System.out.print('*' + ' ');
}
}
System.out.println();
}
System.out.println();
}
public void solve() {
backtrack(0);
}
public static void main(String[] args) {
NQueen nQueen = new NQueen(8);
nQueen.solve();
}
}
原文地址: https://www.cveoy.top/t/topic/nW2U 著作权归作者所有。请勿转载和采集!