51. N 皇后
LeetCode刷题打卡第033天 (第1篇) 202100811
题目链接
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > ans;
vector<string> board(n,string(n,'.'));
vector<bool>visited_col(n,false);
backtracking(ans,board,visited_col,n,0);
return ans;
}
void backtracking(vector<vector<string> >&ans,vector<string> &board,vector<bool>& visited_col,int n,int row){
if(row==n){
ans.push_back(board);
return;
}
for(int i=0;i<n;i++){
if(!judge(board,visited_col,n,row,i)) continue;
visited_col[i]=true;
board[row][i]='Q';
backtracking(ans,board,visited_col,n,row+1);
visited_col[i]=false;
board[row][i]='.';
}
}
bool judge(vector<string>& board,vector<bool>& visited_col,int n,int row,int col){
if(visited_col[col]) return false;
for (int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q') {
return false;
}}
return true;
}
};
|