Skip to content

Commit f540079

Browse files
add N Queens (51.cpp)
1 parent 51e7b22 commit f540079

File tree

1 file changed

+52
-0
lines changed
  • leetcode/cpp/backtracking

1 file changed

+52
-0
lines changed

leetcode/cpp/backtracking/51.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#define f first
2+
#define s second
3+
class Solution {
4+
private:
5+
int n;
6+
vector<string> board;
7+
vector<vector<string>> res;
8+
9+
void solve(int row) {
10+
if (row == n) {
11+
res.push_back(board);
12+
return;
13+
}
14+
15+
for (int col = 0; col < n; ++col)
16+
{
17+
board[row][col] = 'Q';
18+
if (valid(row, col)) {
19+
solve(row+1);
20+
}
21+
board[row][col] = '.';
22+
}
23+
}
24+
25+
bool valid(int ROW, int COL) {
26+
vector<pair<int,int>> dirs =
27+
{{-1,-1}, {-1,0}, {-1,1},
28+
{0, -1}, {0,1},
29+
{1, -1}, {1, 0}, {1,1}};
30+
for (auto d: dirs) {
31+
int k = 1;
32+
int nr = ROW + k*d.f, nc = COL + k*d.s;
33+
while (nr < n && nc < n && nr >= 0 && nc >= 0) {
34+
if (board[nr][nc] == 'Q')
35+
return false;
36+
k++;
37+
nr = ROW + k*d.f;
38+
nc = COL + k*d.s;
39+
}
40+
}
41+
42+
return true;
43+
}
44+
45+
public:
46+
vector<vector<string>> solveNQueens(int n) {
47+
this->n = n;
48+
this->board = vector<string> (n, string (n, '.'));
49+
solve(0);
50+
return res;
51+
}
52+
};

0 commit comments

Comments
 (0)