51. N 皇后
定义棋盘
vector<string> chessboard(n,string(n,'.'));
class Solution {
public:
bool isvalid(int row,int col,int n,vector<string>& chessboard)
{
//由于遍历的时候每一行只会有一个Q,所以不用判断行
//判断列
for(int i=0;i<row;i++)
{
if(chessboard[i][col]=='Q')
return false;
}
//判断左上角
for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--)
{
if(chessboard[i][j]=='Q')
return false;
}
//判断右上角
for(int i=row-1,j=col+1;i>=0&&j<n;i--,j++)
{
if(chessboard[i][j]=='Q')
return false;
}
return true;
}
void backtracking(int n,int row,vector<string>& chessboard)
{
if(row==n)
{
result.push_back(chessboard);
return;
}
for(int col=0;col<n;col++)
{
if(isvalid(row,col,n,chessboard))
{
chessboard[row][col]='Q';
backtracking(n,row+1,chessboard);
chessboard[row][col]='.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> chessboard(n,string(n,'.'));
backtracking(n,0,chessboard);
return result;
}
vector<vector<string>> result;
};