`

Leetcode - N Queues II

 
阅读更多
[分析] 做完N皇后第一题,这个就so easy~

public class Solution {
    public int totalNQueens(int n) {
        int[] rows = new int[n]; // rows[i] = j, means board[i][j] = Q
        int[] cols = new int[n]; // cols[j] = i, means board[i][j] = Q
        for (int i = 0; i < n; i++) {
            rows[i] = -1;
            cols[i] = -1;
        }
        return recur(n, 0, rows, cols);
    }
    
    public int recur(int n, int r, int[] rows, int[] cols) {
        if (r == n) {
            return 1;
        }
        int result = 0;
        for (int j = 0; j < n; j++) {
            if (cols[j] == -1 && verifyDiagnal(rows, r, j)) {
                rows[r] = j;
                cols[j] = r;
                result += recur(n, r + 1, rows, cols);
                rows[r] = -1;
                cols[j] = -1;
            }
        }
        return result;
    }
    
    public boolean verifyDiagnal (int[] rows, int r, int c) {
        for (int i = 0; i < r; i++) {
            if (r - i == Math.abs(c - rows[i]))
                return false;
        }
        return true;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics