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

[Leetcode] N-Queens II

时间:2014-10-18 07:32:25      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

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

标签:style   blog   http   color   io   ar   for   sp   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!