要求:不在横竖斜线
思路:回溯
class Solution {
public:
vector<vector<string>> v;
vector<vector<int>> q;
bool inrow(int i,vector<string> &board){
for(int k=0;k<board.size();++k)
if(board[i][k]=='Q')return true;
return false;
}
bool incol(int j,vector<string> &board){
for(int k=0;k<board.size();++k)
if(board[k][j]=='Q')return true;
return false;
}
bool inlin(int i,int j,vector<string> &board){
for(int k=0;k<q.size();++k)
if(abs(i-q[k][0])==abs(j-q[k][1]))return true;
return false;
}
void dfs(int n,vector<string> &board,int start){
if(n==q.size()){
v.push_back(board);
return;
}
for(int i=start;i<n;++i){
for(int j=0;j<n;++j){
if(!inrow(i,board)&&!incol(j,board)&&!inlin(i,j,board)){
board[i][j]='Q';
q.push_back({i,j});
dfs(n,board,i+1);
q.pop_back();
board[i][j]='.';
}
}
}
}
vector<vector<string>> solveNQueens(int n) {
string row = string(n, '.');
vector<string> board(n,row);
dfs(n,board,0);
return v;
}
};