在 8×8 國際象棋棋盤上放置 8 個皇后,使任兩皇后均不在同一列、同一行、同一斜線上。求所有合法擺放方案總數(已知為 92 種)。
逐行嘗試放置皇后:
column[9]:索引 1~8 對應 8 列,1=被佔用rsl[17]:右上→左下斜線(行+列),範圍 2~16lsl[17]:左上→右下斜線(行-列+8),範圍 1~15queen[9]:記錄每行皇后所在列(可選,用於輸出具體解)public class EightQueens {
private int[] column = new int[9];
private int[] rsl = new int[17]; // row + col
private int[] lsl = new int[17]; // row - col + 8
private static int solutionCount = 0;
public void backtrack(int row) {
if (row > 8) {
solutionCount++;
// 可在此印出 queen[1..8] 具體座標
return;
}
for (int col = 1; col <= 8; col++) {
if (column[col] == 0 && rsl[row + col] == 0 && lsl[row - col + 8] == 0) {
// 放置皇后
column[col] = rsl[row + col] = lsl[row - col + 8] = 1;
// queen[row] = col; // 記錄解
backtrack(row + 1);
// 回溯:撤銷佔用
column[col] = rsl[row + col] = lsl[row - col + 8] = 0;
}
}
}
public static void main(String[] args) {
EightQueens eq = new EightQueens();
eq.backtrack(1);
System.out.println("總解數:" + solutionCount); // 輸出 92
}
}
int 位元掩碼取代陣列,單指令完成衝突檢測(LeetCode 51/52 標準解法)八皇后是回溯法的經典入門題。關鍵在於:狀態表示簡潔、衝突檢測 O(1)、遞入遞出對稱修改狀態。掌握此模板,即可應對所有「在約束條件下尋找所有可行解」的組合優化問題。