LeetCode51 n-皇后 发表于 2021-07-16 | 分类于 LeetCode | 字数统计: 228 | 阅读时长 ≈ 1 链接:https://leetcode-cn.com/problems/n-queens/description/ 题面经典的N皇后问题,要求所有皇后互相不冲突的解法 解法经典的回溯解法学习一下对角线的标记方法,之前学过可能忘记了重温一下 代码1234567891011121314151617181920212223242526class 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; }};