首页 > 其他 > 详细

[Leetcode] N-Queens II

时间:2014-10-18 07:30:45      阅读:120      评论:0      收藏:0      [点我收藏+]

Follow up for N-Queens problem.

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

bubuko.com,布布扣

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;
    }
}

 

[Leetcode] N-Queens II

原文:http://www.cnblogs.com/Phoebe815/p/4032470.html

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