N-Queens II

来源:互联网 发布:华道数据怎么样 编辑:程序博客网 时间:2024/05/16 11:28

N-Queens II


Follow up for N-Queens problem.

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

Please refer to the N-queens.

public class Solution {    public int totalNQueens(int n) {        List<Integer> ret = new ArrayList<Integer>();        ret.add(0);                helper(n,0,new int[n],ret);                return ret.get(0);    }        private void helper(int n, int row, int[] columnForRow, List<Integer> ret) {        if (n == row) {            ret.set(0, ret.get(0)+1);            return;        }         for (int i = 0; i < n; i++) {            columnForRow[row] = i;            if (check(row, columnForRow)) {                helper(n, row + 1, columnForRow, ret);            }        }            }            private boolean check(int row, int[] columnForRow) {        for (int i = 0; i < row; i++) {            if (columnForRow[i] == columnForRow[row] || Math.abs(columnForRow[i] - columnForRow[row]) == row - i)                return false;        }                return true;    }}



 

0 0
原创粉丝点击