N-Queens II

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;
    }
};


你可能感兴趣的:(N-Queens II)