n-皇后问题

题目如下:

The n-queens puzzle is the problem of placing n queens on annn 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:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

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

思路:先定义一个数组pArray[n],数组中第i个数字表示位于第i行的皇后的列号。先把pArray数组初始化,接下来我们要做的事情就是对数组pArray做全排列。由于我们是用不同的数字初始化数组中的数字,因此任意两个皇后肯定不同列。我们只需要判断得到的每一个排列对应的任意两个皇后是不是在同一对角斜线上,也就是数组的两个下标i和j,是不是i-j==pArray[i]pArray[j]或者j-i==pArray[i]-pArray[j]

对于求出了一个正确的数组,就可以将此数组转化为矩阵了,这里需要利用到一个概念:一个n-皇后矩阵的转置还是n-皇后矩阵。具体证明很简单,我在这就不给出了。

    void swap(int *p1,int *p2)

    {
        int temp=*p1;
        *p1=*p2;
        *p2=temp;
    }
    bool Check(int *p,int n)
    {
        bool cheak = true;
        for(int i=0;i<n-1;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(((j-i)==(p[j]-p[i]))||((i-j)==(p[j]-p[i])))
                {
                    cheak=false;
                    i=n;
                    break;
                }
            }
        }
        return cheak;
    }
    void FallArray(int *p,int n,int m,vector<vector<string> > &result)
    {
        if(m==n)
        {
            if(Check(p,n))
            {
                vector<string> tp;
                for(int i=0;i<n;i++)
                {
                    string temp;
                    for(int j=0;j<n;j++)
                    {
                        if(p[i]==j)temp+='Q';
                        else temp+='.';
                    }
                    tp.push_back(temp);
                }
                result.push_back(tp);
            }
        }
        else
        {
            for(int i=m;i<n;i++)
            {
                swap(p+i,p+m);
                FallArray(p,n,m+1,result);
                swap(p+i,p+m);
            }
        }
    }
    vector<vector<string> > solveNQueens(int n)
    {
        vector<vector<string> > result;
        if(n<=0) return result;
        int *pArray=new int[n];
        for(int i=0;i<n;i++)pArray[i]=i;
        FallArray(pArray,n,0,result);
        delete []pArray;
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值