Skip to content

Commit 68e797a

Browse files
Merge pull request #30 from jpriyanshu1406/leetpj
Solutions for N QUEENS Priyanshu Jaiswal
2 parents 5fb0450 + 785a241 commit 68e797a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

N QUEENS

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
vector<vector<string>> solveNQueens(int n) {
4+
vector<vector<string>> ans;
5+
dfs(n, 0, vector<bool>(n), vector<bool>(2 * n - 1), vector<bool>(2 * n - 1),
6+
vector<string>(n, string(n, '.')), ans);
7+
return ans;
8+
}
9+
10+
private:
11+
void dfs(int n, int i, vector<bool>&& cols, vector<bool>&& diag1,
12+
vector<bool>&& diag2, vector<string>&& board,
13+
vector<vector<string>>& ans) {
14+
if (i == n) {
15+
ans.push_back(board);
16+
return;
17+
}
18+
19+
for (int j = 0; j < n; ++j) {
20+
if (cols[j] || diag1[i + j] || diag2[j - i + n - 1])
21+
continue;
22+
board[i][j] = 'Q';
23+
cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true;
24+
dfs(n, i + 1, move(cols), move(diag1), move(diag2), move(board), ans);
25+
cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false;
26+
board[i][j] = '.';
27+
}
28+
}
29+
};

0 commit comments

Comments
 (0)