-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy path51.N-Queens.cpp
69 lines (64 loc) · 1.41 KB
/
51.N-Queens.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
bool issafe(int row,int col,vector<string>&board,int n)
{
int x=row;
int y=col;
// check for row
while(y>=0)
{
if(board[x][y]=='Q')
return false;
y--;
}
// check for diagonals
x=row;
y=col;
while(x>=0 && y>=0)
{
if(board[x][y]=='Q')
return false;
x--;
y--;
}
x=row;
y=col;
while(x<n && y>=0)
{
if(board[x][y]=='Q')
return false;
x++;
y--;
}
return true;
}
void solve(int col,vector<vector<string>> &ans, vector<string> &board,int n)
{
// base case
if(col==n)
{
ans.push_back(board);
return;
}
for(int row=0;row<n;row++)
{
if(issafe(row,col,board,n))
{
board[row][col]='Q';
solve(col+1,ans,board,n);
board[row][col]='.';
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n);
string s(n,'.');
for(int i=0;i<n;i++)
{
board[i]=s;
}
vector<vector<string>> ans;
solve(0,ans,board,n);
return ans;
}
};