N-Queens 解答
2015-10-18 03:50
507 查看
Question
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where
'Q'and
'.'both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
Solution
N-queens问题是NP问题。基本思想其实是用brute-force列举出所有可能然后检查。这里我们可以用一维数组来表示棋盘。A[rowNum] = colNum代表(rowNum, colNum)处是queen。
用迭代的方法进行层层遍历。
到第x行时,说明前(x - 1)行的queen放置都合法。
那我们就遍历前(x - 1)行的结果,如果当前第x行放置的点:
1. 列的值与之前的重复 --> false
2. (行 + 列)或 (行 - 列)的值和之前的 (行 + 列)或(行 - 列)的值相同 --> false
注意对于这题,因为是用一维数组表示棋盘,所以我们不用恢复迭代时设置的queen的位置值。
(参考:CodeGanker, 小莹子)
public class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> result = new ArrayList<List<String>>(); // Here, we use a 1-D array to represent queen positions // queen[1] = 2 means that on (1, 2), there is a queen int[] queen = new int ; helper(n, 0, result, queen); return result; } private void helper(int n, int rowNum, List<List<String>> result, int[] queen) { if (rowNum == n) { List<String> oneResult = new ArrayList<String>(); // Current chess board is valid for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(n); int tmp = n; while (tmp > 0) { sb.append("."); tmp--; } int column = queen[i]; sb.replace(column, column + 1, "Q"); oneResult.add(sb.toString()); } result.add(oneResult); return; } for (int i = 0; i < n; i++) { queen[rowNum] = i; if (check(rowNum, queen)) helper(n, rowNum + 1, result, queen); } } private boolean check(int rowNum, int[] queen) { int colNum = queen[rowNum]; for (int i = 0; i < rowNum; i++) { if (queen[i] == colNum || (queen[i] + i == rowNum + colNum) || (queen[i] - i == colNum - rowNum)) return false; } return true; } }
相关文章推荐
- StringBuffer与StringBuilder原理与区别
- Hibernate中单向一对多,单向多对一,双向一对多 inverse="true" casecade="save-update"的理解
- Mod 与 RequireJS/SeaJS 的那些事
- Permutation Sequence 解答
- android多分辨率多屏幕密度下UI适配方案
- 2015 NEERC F. Gourmet and Banquet
- 控制器管理UINavigationController、UINavigationBar
- UIScrollView
- 物理引擎UIDynamic
- 呈现样式UIModalPresentation
- Hibernate的命名查询(NamedQuery)
- 百度编辑器ueditor的简单使用
- QuickFix/N简介
- QuickFIX/N入门:(三)如何配置QuickFIX/N
- InvokeRequired和Invoke
- HDU 5504 GT and sequence(排除陷阱就是正解)——BestCoder Round #60
- hdoj 5504 GT and sequence 【脑子 抽了】
- October Challenge 2015 Rupsa and Equilateral Triangle
- HDU GT and sequence (数的乘积最大)
- /proc/cpuinfo 文件分析(查看CPU信息)