N-Queens II

Description:

Follow up for N-Queens problem.

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

Code:

#define NUM 100
int x[NUM];
class Solution {
public:
    bool isValid(int k)
    {
        for (int i = 1; i < k; ++i)
        {
            if (x[i] == x[k] || abs(k-i)==abs(x[k]-x[i]) )
                return false;
        }
        return true;
    }
    int totalNQueens(int n) {
        
       for (int i = 0; i < NUM; ++i)
        x[i] = 0;
        
        int k = 1,number = 0;
        while ( k >= 1 )
        {
            x[k]+=1;
            while (x[k] <= n && !isValid(k))
                x[k]+=1;
            if ( x[k] <= n && k == n)
            {
                number++;
            }
            else if ( x[k] <= n && k < n)
            {
                k = k+1;
            }
            else
            {
                x[k] = 0;
                k = k-1;
            }
        }
        return number;
    }
};

 

posted @ 2015-09-06 08:35  Rosanne  阅读(140)  评论(0编辑  收藏  举报