DFS method:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > res;
vector<string> board;
for(int i=0;i<n;i++)
{
string s;
for(int j=0;j<n;j++)
s+='.';
board.push_back(s);
}
solver(res,board,0,n);
return res;
}
void solver(vector<vector<string> >& res, vector<string> board, int row, int n)
{
if(row==n)
res.push_back(board);
for(int j=0;j<n;j++)
{
if(isValid(board,row,j,n))
{
board[row][j]='Q';
solver(res,board,row+1,n);
board[row][j]='.';
}
}
}
bool isValid(vector<string> board, int row, int col, int n)
{
int i,j;
for(i=0;i<row;i++)
if(board[i][col]=='Q')
return false;
for(i=row-1,j=col-1;i>=0&&j>=0;i--,j--)
if(board[i][j]=='Q')
return false;
for(i=row-1,j=col+1;i>=0&&j<n;i--,j++)
if(board[i][j]=='Q')
return false;
return true;
}
};
Updated version, using 3 arrays to check the validation. The three arrays are for the column, 45 degree line and 135 degree line.
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > res;
vector<string> board(n,string(n,'.'));
vector<bool> v_col(n,0);
vector<bool> v_45(2*n-1,0),v_135(2*n-1,0);
helper(n,0,res,board,v_col,v_45,v_135);
return res;
}
void helper(int n,int row,vector<vector<string> >& res,vector<string>& board,vector<bool>& v_col,vector<bool>& v_45,vector<bool>& v_135)
{
if(row==n)
res.push_back(board);
for(int i=0;i<n;i++)
{
int idx_col=i,idx_45=n-1-row+i,idx_135=row+i;
if(v_col[idx_col]==0&&v_45[idx_45]==0&&v_135[idx_135]==0)
{
board[row][i]='Q';
v_col[idx_col]=1;
v_45[idx_45]=1;
v_135[idx_135]=1;
helper(n,row+1,res,board,v_col,v_45,v_135);
board[row][i]='.';
v_col[idx_col]=0;
v_45[idx_45]=0;
v_135[idx_135]=0;
}
}
}
};