leetcode:N-Queens II 【Java】
2016-03-15 16:16
162 查看
一、问题描述
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
![](http://img.blog.csdn.net/20160315161556821)
二、问题分析
参考问题leetcode:N-Queens 【Java】
三、算法代码
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
二、问题分析
参考问题leetcode:N-Queens 【Java】
三、算法代码
public class Solution { public int totalNQueens(int n) { int [] total = new int [] {0}; if (n <= 0) return total[0]; char[][] board = new char ; for (char[] row : board) { Arrays.fill(row, '.'); } boolean[] col_occupied = new boolean ; placeQueen(total, board, col_occupied, 0, n); return total[0]; } private void placeQueen(int [] total, char[][] board, boolean[] col_occupied, int rowNum, int n) { if (rowNum == n) { total[0]++; return; } for (int colNum = 0; colNum < n; colNum++) { if (isValid(board, col_occupied, rowNum, colNum, n)){ board[rowNum][colNum] = 'Q'; col_occupied[colNum] = true; placeQueen(total, board, col_occupied, rowNum + 1, n); board[rowNum][colNum] = '.'; //回溯,尝试皇后rowNum的下一个位置 col_occupied[colNum] = false; } } } private boolean isValid(char[][]board, boolean[] col_occupied, int row, int col, int n) { if (col_occupied[col]) return false; for (int i = 1; row - i >= 0 && col - i >= 0; i++) {//反对角斜线 if (board[row - i][col - i] == 'Q') return false; } for (int i = 1; row - i >= 0 && col + i < n; i++) {//正对角斜线 if (board[row - i][col + i] == 'Q') return false; } return true; } }
相关文章推荐
- Android requires compiler compliance level 5.0 or 6.0. Found '1.4' instead
- leetcode:N-Queens 【Java】
- iOS-UIView 之 layoutMargins & preservesSuperviewLayoutMargins 解惑
- 10个顶级的CSS UI开源框架
- getBuiltInDisplay
- 158.Which statements are true regarding the FOR UPDATE clause in a SELECT statement? (Choose all tha
- NSBundleResourceRequest
- iOS 7及以上,随时改变UIStatusBar颜色
- iOS边练边学--UITableViewCell的常见属性设置
- iOS开发之UITextView,设置textView的行间距及placeholder
- ERROR: '/usr/local/bin' is not writable - it is required for Homebrew, try 'brew doctor' to fix it!
- Android Volley完全解析(三),定制自己的Request
- 从零开始学习EasyDarwin之无锁队列
- com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileExcep
- Java 工具类 ToStringBuilder
- 给按钮UIButton设置图片,setBackGroundImage和setImage两个方法的区别
- quilt.mk源码
- 创建请求集
- UIKeyboard 键盘
- Java.util.concurrent包学习(一) BlockingQueue接口