N-Queens II

来源:互联网 发布:tp5框架隐藏index.php 编辑:程序博客网 时间:2024/06/15 06:58

Follow up for N-Queens problem.

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


Analysis: DFS. The basic logic is the same as N-Queens. 

public class Solution {        public int totalNQueens(int row, int ways, int[] existQueens) {        if(row==existQueens.length) return 1;                for(int col=0; col<existQueens.length; col++) {            boolean satisfied = true;            for(int i=0; i<=row; i++) {                if(existQueens[i]==col || Math.abs(i-row)==Math.abs(existQueens[i]-col)) {                    satisfied = false;                    break;                }            }            if(satisfied) {                existQueens[row] = col;                ways += totalNQueens(row+1, 0, existQueens);                existQueens[row] = Integer.MIN_VALUE;            }        }        return ways;    }        public int totalNQueens(int n) {        int[] existQueens = new int[n];        Arrays.fill(existQueens, Integer.MIN_VALUE);        return totalNQueens(0, 0, existQueens);    }}

0 0