Thursday, January 29, 2015

N-Queens II LeetCode

Here is the solution for the N-Queens II

It is easier than N-Queens.

int total;
    public int totalNQueens(int n) {
        total = 0;
        int[] loc = new int[n];
        dfs(loc, 0, n);
        return total;
    }
   
    private void dfs(int[] loc, int curr, int n) {
        if (curr == n) {
            total++;
            return;
        }
        for (int i=0; i<n; i++) {
            loc[curr] = i;
            if (isValid(loc, curr)) {
                dfs(loc, curr+1, n);
            }
        }
    }
   
    private boolean isValid(int[] loc, int curr) {
        for (int i=0; i<curr; i++) {
            if (loc[curr]==loc[i] || Math.abs(loc[curr] - loc[i]) == (curr-i)) {
                return false;
            }
        }
        return true;
    }

No comments:

Post a Comment