首页 > 代码库 > N-Queens

N-Queens

敲到n皇后,map一下算法,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