LeetCode51 n-皇后

链接https://leetcode-cn.com/problems/n-queens/description/

题面

经典的N皇后问题,要求所有皇后互相不冲突的解法

解法

经典的回溯解法
学习一下对角线的标记方法,之前学过可能忘记了
重温一下

代码

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
class Solution {
public:
vector<vector<string>> boards;
void backtrack(vector<string>& cur, vector<bool>& col, vector<bool>& ld, vector<bool>& rd, int pos, int n) {
if (pos == n) {
boards.push_back(cur);
return;
}
for (int i = 0; i < n; i++) {
if (col[i] || rd[pos + i] || ld[n + pos - i]) {
continue;
}
col[i] = rd[pos + i] = ld[n + pos - i] = 1;
cur[pos][i] = 'Q';
backtrack(cur, col, ld, rd, pos + 1, n);
cur[pos][i] = '.';
col[i] = rd[pos + i] = ld[n + pos - i] = 0;
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> currBoard(n, string(n, '.'));
vector<bool> col(n, false), ld(2 * n + 1, false), rd(2 * n + 1, false);
backtrack(currBoard, col, ld, rd, 0, n);
return boards;
}
};