forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueenEfficient
42 lines (37 loc) · 1.35 KB
/
NQueenEfficient
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
class Solution {
public:
void solve(int col, vector<string> &board, vector<vector<string>> &ans,
vector<int> &leftRow,
vector<int> &upperDiagonal, vector<int> &lowerDiagonal, int n) {
if(col == n) {
ans.push_back(board);
return;
}
for(int row = 0;row<n;row++) {
if(leftRow[row]==0 && lowerDiagonal[row + col] == 0
&& upperDiagonal[n-1 + col - row] == 0) {
board[row][col] = 'Q';
leftRow[row] = 1;
lowerDiagonal[row+col] = 1;
upperDiagonal[n-1 + col - row] = 1;
solve(col+1, board, ans, leftRow, upperDiagonal, lowerDiagonal, n);
board[row][col] = '.';
leftRow[row] = 0;
lowerDiagonal[row+col] = 0;
upperDiagonal[n-1 + col - row] = 0;
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> ans;
vector<string> board(n);
string s(n, '.');
for(int i = 0;i<n;i++) {
board[i] = s;
}
vector<int> leftRow(n, 0), upperDiagonal(2 * n - 1, 0), lowerDiagonal(2 * n - 1, 0);
solve(0,board, ans, leftRow, upperDiagonal, lowerDiagonal, n);
return ans;
}
};