-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN-Queens.cpp
More file actions
37 lines (34 loc) · 1.1 KB
/
N-Queens.cpp
File metadata and controls
37 lines (34 loc) · 1.1 KB
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
// Source: https://leetcode.com/problems/n-queens/
// Author: Miao Zhang
// Date: 2021-01-12
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
string a;
for (int i = 0; i < n; i++) a += '.';
vector<string> board(n, a);
dfs(board, n, 0, res);
return res;
}
void dfs(vector<string>& board, int n, int row, vector<vector<string>>& res) {
if (row == n) {
res.push_back(board);
return;
}
for (int j = 0; j < n; j++) {
if (!canPlace(row, j, n, board)) continue;
board[row][j] = 'Q';
dfs(board, n, row + 1, res);
board[row][j] = '.';
}
}
bool canPlace(int row, int col, int n, vector<string>& board) {
for (int i = 1; i < (row + 1); i++) {
if (board[row - i][col] == 'Q') return false;
if (col - i >= 0 && board[row - i][col - i] == 'Q') return false;
if (col + i < n && board[row - i][col + i] == 'Q') return false;
}
return true;
}
};