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

    Description:

    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:

    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]

    Code:

    class Solution {
    public:
    int x[100];
    bool place(int k)//考察皇后k放置在x[k]列是否发生冲突
    {
        int i;
        for(i=1;i<k;i++)
            if(x[k]==x[i]||abs(k-i)==abs(x[k]-x[i]))
                return false;
            return true;
    }
    
    vector<string> toVectorString(int n)
    {
        vector<string>result;
        for (int i = 1; i <= n; ++i)
        {
            string str(n,'.');
            str[x[i]-1]='Q';
            result.push_back(str);
        }
        return result;
    }
    
        vector<vector<string>> solveNQueens(int n) {
        vector< vector<string> >result;
       for(int i=1;i<=n;i++)
            x[i]=0;
        int k=1;
        while(k>=1)
        {//x[1]...x[n]表示第k个皇后在第x[k]列
            x[k]=x[k]+1;   //在下一列放置第k个皇后
            while(x[k]<=n&&!place(k))
                x[k]=x[k]+1;//搜索下一列
            if(x[k]<=n&&k==n)//得到一个输出
            {
                vector<string>temp = toVectorString(n);
                result.push_back(temp);
            }
            else if(x[k]<=n&&k<n)
                k=k+1;//放置下一个皇后
            else
            {
                x[k]=0;//重置x[k],回溯
                k=k-1;
            }
        }
        return result;
        }
    };
  • 相关阅读:
    爬取B站up主相册原图
    爬MEIZITU网站上的图片
    mpvue
    修改Tomcat控制台标题
    iserver频繁崩溃、内存溢出事故解决小记
    Java反射机制详解 及 Method.invoke解释
    window下maven的环境搭建
    window下mongodb的安装和环境搭建
    centos7 安装 redis4.0.8
    centos7 安装mysql5.7.20(yum方式)
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4783477.html
Copyright © 2011-2022 走看看