n皇后问题的递归和迭代版 leetcode N-Queens
Posted lakeone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了n皇后问题的递归和迭代版 leetcode N-Queens相关的知识,希望对你有一定的参考价值。
题目如下图:
递归版
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<int> dict(n, 0); dfs(0, dict, n); return res; } private: void dfs(int cur, vector<int> & dict, int n) { if (cur == n) { fillRes(dict); return; } for (int i = 0; i < n; i++) { dict[cur] = i; if (check(dict, cur)) dfs(cur + 1, dict, n); } } void fillRes(vector<int> & dict) { vector<string> tmp; for (int i = 0; i < dict.size(); i++) { string s(dict.size(), ‘.‘); s[dict[i]] = ‘Q‘; tmp.push_back(s); } res.push_back(tmp); } bool check(vector<int> & dict, int cur) { for (int i = 0; i < cur; i++) { if (dict[i] == dict[cur] || abs(dict[cur] - dict[i]) == abs(cur - i)) return false; } return true; } vector<vector<string>> res; };
迭代版
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> res; vector<int> nums(n, 0); int cur = 0; while (cur >= 0) { if (check(nums, cur)) cur = cur + 1; else { int carry = 1; for (; cur >= 0 && carry != 0;) { nums[cur] += carry; if (nums[cur] == n) { nums[cur--] = 0; carry = 1; } else { carry = 0; } } } if (cur == n) { fillRes(res, nums); int carry = 1; for (cur--; cur >= 0 && carry != 0;) { nums[cur] += carry; if (nums[cur] == n) { nums[cur--] = 0; carry = 1; } else { carry = 0; } } } } return res; } private: void fillRes(vector<vector<string>> & res, vector<int> & dict) { vector<string> tmp; for (int i = 0; i < dict.size(); i++) { string s(dict.size(), ‘.‘); s[dict[i]] = ‘Q‘; tmp.push_back(s); } res.push_back(tmp); } bool check(vector<int> & dict, int cur) { for (int i = 0; i < cur; i++) { if (dict[i] == dict[cur] || abs(dict[cur] - dict[i]) == abs(cur - i)) return false; } return true; } };
以上是关于n皇后问题的递归和迭代版 leetcode N-Queens的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 51. N-Queens N 皇后(困难)