參考
n皇后問題是將n個皇后放置在n*n的棋盤上,皇后彼此之間不能相互攻擊。
給定一個整數(shù)n,返回所有不同的n皇后問題的解決方案。
每個解決方案包含一個明確的n皇后放置布局,其中“Q”和“.”分別表示一個女王和一個空位置。
您在真實的面試中是否遇到過這個題? Yes
樣例
對于4皇后問題存在兩種解決的方案:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
#define INITIAL -1000
bool isValid(vector<int> &table,int row,int col,int n) {
for(int i = 0;i < n;i++) {
if (table[i] == col || abs(i-row) == abs(table[i]-col)) {
return false;
}
}
return true;
}
vector<string> getOneResult(vector<int> &table,int n) {
string a(n,'.');
vector<string> result(n,a);
for(int i = 0;i < n;i++) {
string temp = result[i];
temp[table[i]] = 'Q';
result[i] = temp;
}
return result;
}
vector<vector<string> > solveNQueens(int n) {
// write your code here
vector<vector<string> > results;
vector<int> table(n,INITIAL);
int i = 0;
int j = 0;
while(i < n) {
while(j < n) {
if (isValid(table,i,j,n) == true) {
table[i] = j;
j = 0;
break;
} else {
++j;
}
} //這個j循環(huán)找到適合的放置地點,若找不到table[i] == INITIAL
if (table[i] == INITIAL) {
if(i == 0) {
break;//回溯到第一行沒解就終止
} else {
i--;//回溯上一行的下一列
j = table[i] + 1;
table[i] = INITIAL;
continue;
}
}
if (i == n-1) { //最后一行打印
results.push_back(getOneResult(table,n));
j = table[i] + 1;
table[i] = INITIAL;
continue;
}
i++;
}
return results;
}
};
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。