Saturday, March 9, 2013

[LeetCode] N Queen II

Thought:
It is much easier than the previous problem.

Code:
public class Solution {
    int[] cache;
    int result;
    public int totalNQueens(int n) {
        cache = new int[n];
        result = 0;
        placeQueen(0, n);
        return result;
    }
    public boolean check(int row) {
        for (int i = 0; i < row; i++) {
            int dif = Math.abs(cache[i] - cache[row]);
            if (dif == 0 || dif == row - i) return false;
        }
        return true;
    }
    public void placeQueen(int row, int max) {
        if (row == max) {           
            result++;
            return;
        }
        for (int i = 0; i < max; i++) {
            cache[row] = i;
            if (check(row)) placeQueen(row + 1, max);
        }
    }
}

No comments:

Post a Comment