經典回溯問題:在 $N \times N$ 棋盤放置 $N$ 個皇后,使其不互相攻擊 (同行、同列、同對角線)。需按字典序輸出前三組解 (以欄位序列表示) 及總解數。$N \le 13$。
#include
int n, total = 0;
int col[14], diag1[27], diag2[27]; /* 索引上限 2N-1 */
int sol[14]; /* 當前解: sol[row] = col */
void dfs(int row) {
if (row > n) {
total++;
if (total <= 3) {
for (int i = 1; i <= n; i++) {
printf("%d%c", sol[i], i == n ? '\n' : ' ');
}
}
return;
}
for (int c = 1; c <= n; c++) {
if (!col[c] && !diag1[row+c] && !diag2[row-c+n]) {
sol[row] = c;
col[c] = diag1[row+c] = diag2[row-c+n] = 1;
dfs(row + 1);
col[c] = diag1[row+c] = diag2[row-c+n] = 0;
}
}
}
int main() {
scanf("%d", &n);
dfs(1);
printf("%d\n", total);
return 0;
}
2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4