N-Queens II

Follow up for N-Queens problem.

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

class Solution {
public:
    void visit(int n, unsigned int left, unsigned int mid, 
               unsigned int right, int pos, int &result)
    {
	    if (pos >= n)
	    {
		    result++;
		    return;
	    }

	    unsigned int mask = left | mid | right;
	    for (unsigned int i = 0; i < n; i++)
	    {
		    unsigned int a = 1 << i;
		    if (!(a & mask))
		    {
			    visit(n, (left | a) << 1, mid | a, (right | a) >> 1, pos+1, result);
		    }
	    }
    }

    int totalNQueens(int n) {
        int result = 0;
	    visit(n, 0, 0, 0, 0, result);

	    return result;
    }
};


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