-
Notifications
You must be signed in to change notification settings - Fork 3
/
n_queen.cpp
96 lines (71 loc) · 1.9 KB
/
n_queen.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class Solution {
public:
bool safe(int row, int col, vector<string>board, int n)
{
int r = row;
int c = col;
// checking if atttacked by upperleft to down right diagonal
while(row>=0 and col>=0 )
{
if(board[row][col]=='Q')
return false;
col--;
row--;
}
// checking if attacked by current row
row = r;
col = c;
while(row>=0 and col>=0)
{
if(board[row][col]=='Q')
return false;
col--;
}
row=r;
col=c;
// checking if attacked by lower right diagonal
while(row>=0 and col>=0 and row<n)
{
if(board[row][col]=='Q')
return false;
row++;
col--;
}
return true;
}
void solve(int col, vector<string>board, vector<vector<string>>&ans, int n)
{
// base case
if(col>=n)
{
ans.push_back(board);
return;
}
//filling all possible rows of the current column
for(int row=0;row<n;row++)
{
if(safe(row, col, board, n))
{
board[row][col]='Q';
solve(col+1, board, ans, n);
board[row][col]='.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
// n rows
// n columns
vector<vector<string>>ans;
string s="";
for(int i=0;i<n;i++)
s+=".";
vector<string>board(n);
for(int i=0;i<n;i++)
{
board[i]=s;
}
//ans.push_back(board);
solve( 0, board, ans, n);
return ans;
}
};