N 皇后问题leetcode
今天单独写一下n皇后吧,利用回溯吧,赶明写一下回溯的模板写法吧
class Solution
{
public:
vector<vector<string>> solveNQueens(int n)
{
vector<string> board(n,string(n,'.'));
backtrack(board,0);
return result;
}
private:
vector<vector<string>> result;
void backtrack(vector<string> &board,int row)
{
if(row==board.size())
{
result.push_back(board);
return;
}
int n=board[row].size();
for(int col=0; col<n; col++)
{
if(!IsValid(board,row,col))
continue;
board[row][col]='Q';
backtrack(board,row+1);
board[row][col]='.';
}
}
bool IsValid(vector<string> &board,int row,int col)
{
int n=board.size();
for(int i=0; i<n; i++) //检查上方是否冲突
{
if(board[i][col]=='Q')
return false;
}
for(int i=row-1,j=col+1; i>=0&&j<n; i--,j++) //检查右上方是否冲突
{
if(board[i][j]=='Q')
return false;
}
for(int i=row-1,j=col-1; i>=0&&j>=0; i--,j--) //检查左上方是否冲突
{
if(board[i][j]=='Q')
return false;
}
return true;
}
};