zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    

      

  • 相关阅读:
    tree
    gridview XML
    http://jingyan.baidu.com/article/22a299b513f3db9e18376a5e.html
    tree btn
    sss rar jar
    ComponentOne Studio
    http://wpf_sl.cnblogs.com/ WPF/Silverlight深蓝团队
    ddddd
    [牛客每日一题] (前缀和+线性 DP) NC15553 数学考试
    [停更一周,我干了什么] [C++/QT] 一个基于avl树,trie树,哈希散列表的英汉词典
  • 原文地址:https://www.cnblogs.com/tanghulu321/p/3050295.html
Copyright © 2011-2022 走看看