题目:
解答:
使用题51的解法,但是不需要保存记录了。
代码:
class Solution {
public:
bool CheckOK(vector<string>& panel, int row, int col,int n){
for(int i = 0;i < row; ++i)
if(panel[i][col] == 'Q')
return false;
for(int i = row - 1;i >= 0; --i){
if(col + row - i < n && panel[i][col+row-i] == 'Q')
return false;
if(col - row + i >= 0 && panel[i][col-row+i] == 'Q')
return false;
}
return true;
}
int totalNQueens(int n) {
string line(n, '.');
vector<string> chesspanel(n, line);
int row = 0, col = 0;
if(n == 1){
return 1;
}
int cnt = 0;
while(true){
while(row != n){
// 遍历寻找每行的可放置位置
while(col != n){
if(CheckOK(chesspanel, row, col, n)){
chesspanel[row][col] = 'Q';
++row;
col = 0;
break;
}
++col;
}
if(col == n){
while(row > 0){
bool updateOK = false;
for(int i = 0;i < n; ++i){
if(chesspanel[row-1][i] == 'Q'){
if(i != n - 1){
// 如果没有合适的,在将上一行的位置右移一个位置点
chesspanel[row-1][i] = '.';
col = i + 1;
updateOK = true;
--row;
break;
}else{
// 如果上一行已经到了最边缘,递归向上求解,如果到顶层,结束
chesspanel[row-1][i] = '.';
col = 0;
--row;
if(row == 0)
return cnt;
break;
}
}
}
if(updateOK)
break;
}
}
}
++cnt;
row--;
//寻找下一个位置点
for(int i = 0;i < n; ++i)
if(chesspanel[row][i] == 'Q'){
chesspanel[row][i] = '.';
col = i + 1;
break;
}
}
return cnt;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)