首页 > 其他 > 详细

LeetCode - N-Queens II

时间:2015-12-26 18:39:51      阅读:158      评论:0      收藏:0      [点我收藏+]

题目:

Follow up for N-Queens problem.

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

技术分享

思路:

根据N-Queens的方法,设置一个private int count变量

package recursion;

public class NQueensII {
    private int count;
    
    public int totalNQueens(int n) {
        int[] positions = new int[n];
        this.count = 0;
        solve(positions, 0, n);
        return this.count;
    }
    
    private void solve(int[] positions, int row, int n) {
        if (row == n) {
            this.count++;
        } else {
            for (int i = 0; i < n; ++i) {
                if (isValid(positions, row, i)) {
                    positions[row] = i;
                    solve(positions, row + 1, n);
                }
            }
        }
    }
    
    private boolean isValid(int[] positions, int row, int candidate) {
        for (int i = 0; i < row; ++i) {
            if (positions[i] == candidate || Math.abs(i - row) == Math.abs(positions[i] - candidate))
                return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        NQueensII n = new NQueensII();
        System.out.println(n.totalNQueens(4));
    }

}

 

LeetCode - N-Queens II

原文:http://www.cnblogs.com/shuaiwhu/p/5078392.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!