[Leetcode] N-Queens II

Follow up for N-Queens problem.

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

Solution:

N-Queens 问题的简化版。

public class Solution {
    private int ans = 0;

    public int totalNQueens(int n) {
        List<String[]> result = new ArrayList<String[]>();
        if (n == 0)
            return ans;
        int[] rCol = new int[n];
        queens(result, rCol, 0, n);
        return ans;
    }

    private void queens(List<String[]> result, int[] rCol, int row, int n) {
        // TODO Auto-generated method stub
        if (row == n) {
            ans++;
            return;
        }
        for (int col = 0; col < n; ++col) {
            rCol[row] = col;
            if (check(rCol, row)) {
                queens(result, rCol, row + 1, n);
            }
        }
    }

    private boolean check(int[] rCol, int row) {
        // TODO Auto-generated method stub
        for (int i = 0; i < row; ++i) {
            if (rCol[i] == rCol[row])
                return false;
            if (Math.abs(row - i) == Math.abs(rCol[row] - rCol[i])) {
                return false;
            }
        }
        return true;
    }
}

 

posted @ 2014-10-18 07:22  Phoebe815  阅读(112)  评论(0编辑  收藏  举报