个人博客:https://luxialan.com

N-Queens II 分类: Leetcode 2014-12-24 14:17 85人阅读 评论(0) 收藏

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

八皇后问题拖了好久才解决,用的是回溯法的思路,可以用非递归的方法实现,本质上是用栈来实现深度遍历

class Solution {
public:
    int a[1000];
    int count=0;
    bool judge(int n)
    {
        int i;
        for(i=0;i<n;i++)
        {
            if( (a[i]==a[n]) || abs(a[i]-a[n])==abs(i-n) )
            {
                return false;
            }
        }
        return true;
    }
    
    void playchess(int n,int len)
    {
        int i;
        for(i=0;i<len;i++)
        {
            a[n]=i;
            if(judge(n))
            {
                if(n==len-1) count++;
                else
                playchess (n+1,len);
            }
        }
    }
    
    int totalNQueens(int n) {
        int len=n,i;
        for(i=0;i<n;i++)
        {
            a[i]=-1;
        }
        playchess(0,len);
        return count;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2014-12-24 14:17  luxialan  阅读(126)  评论(0编辑  收藏  举报