-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN-Queens
67 lines (52 loc) · 1.63 KB
/
N-Queens
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
// Leetcode --- NQueens
class Solution {
public:
vector<vector<string>> res;
bool Is_queen_safe(vector<string>& chess, int row , int col){
for(int i = row , j= col ; i>=0 ;i--){// checking in upper direction
if(chess[i][j] == 'Q'){
return false;
}
}
for(int i = row , j= col ; i>=0 and j>=0;i-- ,j--){// checking in left diagonal
if(chess[i][j] == 'Q'){
return false;
}
}
for(int i = row , j= col ; i>=0 and j< chess.size();i-- , j++){// checking in right diagonal
if(chess[i][j] == 'Q'){
return false;
}
}
return true;
}
void helper(vector<string>& chess , int row ){
if(row == chess.size()){
res.push_back(chess);
return ;
}
for(int i=0;i<chess.size() ;i++){
if( Is_queen_safe(chess, row , i)){
chess[row][i] = 'Q';
helper(chess , row + 1);
chess[row][i] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
string s;
for(int i=0;i<n;i++){
s.push_back('.');
}
vector<string> chess(n, s);
// initializing a chessboard with -
// . . . .
// . . . .
// . . . .
// . . . .
// this is a chessboard containing string on each row initilizing with n dots
int row = 0;
helper(chess , row );
return res;
}
};