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 totalNQueens(int n) {
        int check[n];
        int sum=0;
        calc(n,check,sum,0);
        return sum;
    }
    void calc(int& n,int* check,int& sum,int step)
    {
        if(step==n)
        {
            sum++;
            return;
        }
        for(int i=0;i<n;i++)
        {
            bool ok=true;
            for(int j=0;j<step;j++)
                if(check[j]==i || i-check[j]==step-j || check[j]-i==step-j)
                {
                    ok=false;
                    break;
                }
            if(ok)
            {
                check[step]=i;
                calc(n,check,sum,step+1);
            }
        }
    }
}; 
posted @ 2014-05-29 16:20  erictanghu  阅读(72)  评论(0编辑  收藏  举报