leetCode51.N皇后
题解分析
代码
class Solution {
public:int n;vector<vector<string>> ans;vector<string> path;vector<bool> col, dg,udg;vector<vector<string>> solveNQueens(int _n) {n = _n;col = vector<bool> (n);dg = udg = vector<bool> (2 * n);path = vector<string> (n, string(n,'.'));dfs(0);return ans;}void dfs(int y){if(y == n){ans.push_back(path);return;}for(int x = 0; x < n; x++){if(!col[x] && !dg[y - x + n] && !udg[y + x]){col[x] = dg[y - x + n] = udg[y + x] = true;path[y][x] = 'Q';dfs(y + 1);path[y][x] = '.';col[x] = dg[y - x + n] = udg[y + x] = false;}}}
};