zoukankan      html  css  js  c++  java
  • N-Queens

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

    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.

    For example,
    There exist two distinct solutions to the 4-queens puzzle:

    分析: 著名的N皇后问题,可以采用一位数组来代替二维数组,利用回溯,注意皇后行走的条件

    class Solution {
    public:
        bool isOk(int start,int value, const vector<int>& array){
            for(int i =start-1; i>=0; i--)
                if((array[i]==value) || (abs(array[i]-value)==abs(start-i)))
                    return false;
            if(abs(array[start-1]-value)==1)
                return false;
            return true;
        }
        void Queen(int start, vector<int>& array, vector<vector<int>> & res ){
            //cout << start <<endl;
            if(start == array.size()){
                res.push_back(array);
                return;
            }
           for(int i =0; i< array.size(); i++){
               if(isOk(start, i, array)){
                  // cout <<"hello"<<endl;
                   array[start] =i;
                   Queen(start+1, array, res);
               }
               
           }
           return;
        }
        
        void convert(const vector<vector<int>> res, vector<vector<string>>& str){
            for(vector<int> t: res){
                int n = t.size();
                vector<string> strlist;
                for(int i=0; i<n; i++){
                    string s(n,'.');
                    s[t[i]] = 'Q';
                    strlist.push_back(s);
                }
                str.push_back(strlist);
                
            }
            
        }
        vector<vector<string>> solveNQueens(int n) {
            vector<vector<int>> res;
            vector<vector<string>> str;
            if(n==0)
                return str;
            vector<int> array(n,0);
            for(int i =0; i< n; i++){
                array[0] =i;
                Queen(1,array,res);
            }
            convert(res,str);
            return str;
            
        }
    };
    

      

  • 相关阅读:
    对文件的操作
    三级菜单优化
    三级菜单项目
    对字符串的操作(一些重要的方法)
    四、saltstack如何管理对象?
    三、saltstack证书管理
    二、saltstack基础配置
    一、saltstack简介和安装
    set集合
    异常处理语法
  • 原文地址:https://www.cnblogs.com/willwu/p/6231223.html
Copyright © 2011-2022 走看看