-
Notifications
You must be signed in to change notification settings - Fork 0
/
Nqueens
76 lines (62 loc) · 1.51 KB
/
Nqueens
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
class Solution {
public:
bool isvalid(int i , int j , vector <string> &board)
{
//leftrow
int n = board.size() ;
for(int k = j; k >= 0 ; k--)
{
if(board[i][k] == 'Q')
return false;
}
//upper diagnol
int a = i ;
int b = j ;
while(a >= 0 && b >= 0)
{
if(board[a][b] == 'Q')
return false;
a-- ;
b-- ;
}
//lower diagnol
a = i ;
b = j ;
while(a < n && b >= 0)
{
if(board[a][b] == 'Q')
return false;
a++ ;
b-- ;
}
return true ;
}
void helper(vector <string> &board , int col , vector <vector <string> > &ans , int n)
{
if(col == n )
{
ans.push_back(board) ;
}
for(int row = 0 ; row < n ; row++ )
{
bool a = isvalid(row , col, board) ;
if(a)
{
board[row][col] = 'Q' ;
helper(board, col + 1, ans , n) ;
board[row][col] = '.' ;
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector <vector <string> > ans ;
vector <string> board ;
string s(n,'.') ;
for(int i = 0 ; i< n ; i++)
{
board.push_back(s) ;
}
helper(board , 0 , ans , n) ;
return ans ;
}
};