Skip to content

Commit ffedf62

Browse files
authored
Merge pull request neetcode-gh#775 from apurvtaneja/patch-1
Solution Taught in the Video
2 parents e5a04c3 + 73cf478 commit ffedf62

File tree

1 file changed

+33
-38
lines changed

1 file changed

+33
-38
lines changed

cpp/neetcode_150/10_backtracking/n-queens.cpp

Lines changed: 33 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,48 +8,43 @@
88
*/
99

1010
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-
}
1811
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
3315

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 ;
3920
}
4021

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] = '.';
4540
}
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;
5449
}
5550
};

0 commit comments

Comments
 (0)