題目
n 皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,並且使皇后彼此之間不能相互攻擊。
上圖爲 8 皇后問題的一種解法。
給定一個整數 n,返回 n 皇后不同的解決方案的數量。
示例:
輸入: 4
輸出: 2
解釋: 4 皇后問題存在如下兩個不同的解法。
[
[".Q..",
"...Q",
"Q...",
"..Q."],
["..Q.",
"Q...",
"...Q",
".Q.."]
]
提示:
皇后,是國際象棋中的棋子,意味着國王的妻子。皇后只做一件事,那就是“喫子”。當她遇見可以喫的棋子時,就迅速衝上去喫掉棋子。當然,她橫、豎、斜都可走一或七步,可進可退。(引用自 百度百科 - 皇后 )
方案:回溯
- 同51,不知道爲啥題號是52,明明應該和51換換的。。。。
class Solution {
private int[] coord;
private int n;
private int total;
public int totalNQueens(int n) {
this.n = n;
this.coord = new int[n];
recall(0);
return total;
}
public void recall(int row){
if (row>=this.n) {
this.total++;
return;
}
loop1:for(int i = 0;i<this.n;i++){
for (int j = 0;j<row;j++){
if (coord[j]==i) continue loop1;
if (coord[j]<i&&coord[j]-j+row==i)continue loop1;
if (coord[j]>i&&coord[j]+j-row==i)continue loop1;
}
this.coord[row] = i;
recall(row+1);
this.coord[row] = 0;
}
return;
}
}
複雜度計算