n 皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上胞锰,并且使皇后彼此之間不能相互攻擊洞焙。
image
上圖為 8 皇后問題的一種解法猾愿。
給定一個整數(shù) n蹋半,返回 n 皇后不同的解決方案的數(shù)量取胎。
示例:
輸入: 4
輸出: 2
解釋: 4 皇后問題存在如下兩個不同的解法。
[
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
思路:
遞歸回溯,每次只考慮安排某一行的皇后闻蛀,如果能遍歷完行res加1匪傍。具體實現(xiàn)如下。
class Solution {
public:
int res;
int totalNQueens(int n) {
if(n<=0) return 0;
vector<int> curr(n,0);
res=0;
putRow(n,0,curr);
return res;
}
void putRow(int n,int row,vector<int> curr)
{
if(row>=n)
{
res++;
return;
}
for(int col=0;col<n;col++)
{
if(isValid(row,col,curr))
{
curr[row]=col;
putRow(n,row+1,curr);
}
}
}
bool isValid(int row,int col,vector<int> curr)
{
for(int i=0;i<row;i++)
{
if(curr[i]==col || abs(i-row)==abs(col-curr[i]))
{
return false;
}
}
return true;
}
};