本文主要是介绍N-Queens,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
敲到n皇后,mark一下算法,num[i]代表i行的位置是num[i],进行全排列
class Solution {
public:vector<vector<string> > res;void helper(vector<int> &nums, int index, int n) {if(index == n) {bool flag = true;for(int i = 0; i < n && flag; i++) for(int j = i+1; j < n; j++) if((j-i) == abs(nums[j]-nums[i])) {flag = false;break;}if(flag) {vector<string> tmp;for(int i = 0; i < n; i++) {string row(n,'.');row[nums[i]] = 'Q';tmp.push_back(row);}res.push_back(tmp);} }for(int i = index; i < n; i++) {swap(nums[index],nums[i]);helper(nums,index+1; n);swap(nums[index],nums[i]);} }vector<vector<string> > solveNQueens(int n) {res.clear();vector<int> nums(n);for(int i = 0; i < n; i++)nums[i] = i;helper(nums,0,n);return res;}
};
这篇关于N-Queens的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!