N queens LeetCode

题目:Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

思路: 回溯法,首先建立一个备选答案的vector,每次向其中添加一个经过检查可以添加的元素,如果搜索深度达到n则将备选答案存储

代码:

class Solution {
public:
    
    
    bool isOK(vector<int> oneSolution, int valToAdd,int k){
        
        
        
        for(int j = 0; j < k; j++){  
            
            if(oneSolution[j] == valToAdd)  
                return false;  
            else if(abs(valToAdd - oneSolution[j]) == abs(j - k))  
                return false;  
        }  
        return true; 
    }
    
    void backtracking(vector<int> oneSolution, int k, int n, vector<vector<string> > &result){
        
        if (k == n){
            vector<string> oneSolutionInChar(n, "");
              for (int i = 0; i < n; i++) 
                  for (int j = 0; j < n; j++) {
                      if (j == oneSolution[i]) oneSolutionInChar[i] += 'Q';
                      else oneSolutionInChar[i] += '.';
                  }
            
            result.push_back(oneSolutionInChar);
        }
        
        else{
            
            k = k+1;
            for (int i = 0; i<n; i++){
                
                if (!isOK(oneSolution, i, k-1)) continue;
                
                oneSolution[k-1] = i;
                backtracking(oneSolution, k, n, result);
            }
        }
    }
    
    vector<vector<string> > solveNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<string> > result;
        if (n == 0) return result;
        
        vector<int> oneSolution(n);
        int k = 0;
        backtracking(oneSolution, k, n, result); 
        return result;
    }
};

  

原文地址:https://www.cnblogs.com/tanghulu321/p/3050295.html