|
8 | 8 | */
|
9 | 9 |
|
10 | 10 | class Solution {
|
11 |
| -public: |
12 |
| - vector<vector<string>> solveNQueens(int n) { |
13 |
| - vector<string> board(n, string(n, '.')); |
14 |
| - vector<vector<string>> result; |
15 |
| - dfs(n, 0, board, result); |
16 |
| - return result; |
17 |
| - } |
18 | 11 | private:
|
19 |
| - void dfs(int n, int row, vector<string>& board, vector<vector<string>>& result) { |
20 |
| - if (row == n) { |
21 |
| - result.push_back(board); |
22 |
| - return; |
23 |
| - } |
24 |
| - |
25 |
| - for (int col = 0; col < n; col++) { |
26 |
| - if (isValid(n, row, col, board)) { |
27 |
| - board[row][col] = 'Q'; |
28 |
| - dfs(n, row + 1, board, result); |
29 |
| - board[row][col] = '.'; |
30 |
| - } |
31 |
| - } |
32 |
| - } |
| 12 | + unordered_set<int> cols; //for Columns |
| 13 | + unordered_set<int> negDiag; //for negative diagnals R-C |
| 14 | + unordered_set<int> posDiag; //for positive diagnals R+C |
33 | 15 |
|
34 |
| - bool isValid(int n, int row, int col, vector<string>& board) { |
35 |
| - for (int i = 0; i < row; i++) { |
36 |
| - if (board[i][col] == 'Q') { |
37 |
| - return false; |
38 |
| - } |
| 16 | + void backtrack(int n, int row, vector<vector<string>>& res, vector<string>& board){ |
| 17 | + if(row==n){ |
| 18 | + res.push_back(board); |
| 19 | + return ; |
39 | 20 | }
|
40 | 21 |
|
41 |
| - for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { |
42 |
| - if (board[i][j] == 'Q') { |
43 |
| - return false; |
44 |
| - } |
| 22 | + for(int col = 0; col < n; col++){ //Shifting through each col |
| 23 | + if( cols.find(col) != cols.end() or //if queen alread placed in this col |
| 24 | + negDiag.find(row - col) != negDiag.end() or //if queen in negDiag |
| 25 | + posDiag.find(row + col) != posDiag.end() //if queen in posDiag |
| 26 | + ) |
| 27 | + continue; |
| 28 | + |
| 29 | + cols.insert(col); |
| 30 | + negDiag.insert(row - col); |
| 31 | + posDiag.insert(row + col); |
| 32 | + board[row][col] = 'Q'; |
| 33 | + |
| 34 | + backtrack(n, row +1, res, board); |
| 35 | + |
| 36 | + cols.erase(col); |
| 37 | + negDiag.erase(row - col); |
| 38 | + posDiag.erase(row + col); |
| 39 | + board[row][col] = '.'; |
45 | 40 | }
|
46 |
| - |
47 |
| - for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { |
48 |
| - if (board[i][j] == 'Q') { |
49 |
| - return false; |
50 |
| - } |
51 |
| - } |
52 |
| - |
53 |
| - return true; |
| 41 | + } |
| 42 | + |
| 43 | +public: |
| 44 | + vector<vector<string>> solveNQueens(int n) { |
| 45 | + vector<vector<string>> res; |
| 46 | + vector<string> board(n, string(n,'.')); |
| 47 | + backtrack(n, 0, res, board); |
| 48 | + return res; |
54 | 49 | }
|
55 | 50 | };
|
0 commit comments