2014年3月17日星期一

LeetCode - N-Queens II



Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.



public class Solution {
    public int totalNQueens(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        assert(n>0);
        return solveNQueens(0,new int[n]);
    }
   
    public int solveNQueens(int n, int[] solves) {
        if(n==solves.length) {
            return 1;
        }
        int ret = 0;
        for(int i=0;i<solves.length;i++) {
            solves[n] = i;
            if(check(n, solves)) {
                ret += solveNQueens(n+1, solves);
            }
        }
        return ret;
    }

    private boolean check(int n, int[] solves) {
        for(int i=0;i<n;i++) {
            if(solves[i]==solves[n] || Math.abs(solves[i]-solves[n])==Math.abs(i-n)) {
                return false;
            }
        }
        return true;
    }
}

没有评论:

发表评论