码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - N-Queens II

时间:2015-12-26 18:40:44      阅读:169      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!