首页 > 代码库 > LeetCode N-Queens
LeetCode N-Queens
class Solution {private: int queen_num; vector<vector<string> > res;public: vector<vector<string> > solveNQueens(int n) { res.clear(); queen_num = n; vector<bool> h(n, false); vector<bool> v(n, false); vector<bool> lx(n * 2 + 1, false); vector<bool> rx(n * 2 + 1, false); vector<int> solution; dfs(solution, h, v, lx, rx); return res; } void dfs(vector<int> &mem, vector<bool> &h, vector<bool> &v, vector<bool> &lx, vector<bool> &rx) { if (mem.size() == queen_num) { add_solution(mem); return; } int row = mem.size(); int col = 0; while (col < queen_num) { if (!h[row] && !v[col] && !lx[row + col] && !rx[row + queen_num - col - 1]) { h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = true; mem.push_back(col); dfs(mem, h, v, lx, rx); mem.pop_back(); h[row] = v[col] = lx[row + col] = rx[row + queen_num - col - 1] = false; } col++; } } void add_solution(vector<int> &solution) { res.push_back(vector<string>()); string line(queen_num, ‘.‘); for (int i=0; i<queen_num; i++) { line[solution[i]] = ‘Q‘; res.back().push_back(line); line[solution[i]] = ‘.‘; } }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。