首页 > 代码库 > [Leetcode] N-Queens II
[Leetcode] N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。