LeetCode-N-Queens
来源:互联网 发布:泰勒展开 矩阵形式 编辑:程序博客网 时间:2024/06/05 02:18
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.."]]八皇后问题的变形题,一个不能再经典的题了。回溯法,要保证任意两各queens都不能再同一行、同一列、同一对角线。代码如下:
public List<List<String>> solveNQueens(int n) { List<List<String>> lists = new ArrayList<List<String>>(); dfs(lists, new int[n], 0); return lists; } private void dfs(List<List<String>> lists, int[] ret, int col) { if (col == ret.length) { List<String> list = new ArrayList<String>(ret.length); for (int p = 0; p < ret.length; p++) { StringBuilder sb = new StringBuilder(); for (int q = 0; q < ret.length; q++) { if (ret[p] == q) sb.append("Q"); else sb.append("."); } list.add(sb.toString()); } lists.add(list); return; } for (int k = 0; k < ret.length; k++) { ret[col] = k; if (check(ret, col)) dfs(lists, ret, col+1); } } private boolean check(int[] ret, int col) { for (int p = 0; p < col; p++) { if (Math.abs(ret[col]-ret[p]) == Math.abs(col-p)) return false; if (ret[col] == ret[p]) return false; } return true; }
其实这里面还是有很多值得研究的,首先搞了一个n长度的一维数组,而不是二维数组,因为数组的下标就代表了第几列,即ret[col] = row, 这是一个很好的优化。我上面是一列一列的扫描的,你也可以一行一行的扫描,都一样,因为这是个n*n的正方形。
0 0
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- LeetCode: N-Queens II
- LeetCode: N-Queens
- LeetCode : N-Queens
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- leetcode 72: N-Queens
- LeetCode 38: N-Queens
- 【leetcode】N-Queens II
- 【leetcode】N-Queens
- LeetCode: N Queens II
- [LeetCode]N-Queens
- [LeetCode]N-Queens II
- [leetcode]N-Queens
- [LeetCode] Anagrams、N-Queens
- stl_function.h
- SOA概念解惑
- 玛丽卡 (codevs p1021;洛谷p1186)
- SP800-53实现安全分级
- O2O平台盈利模式有哪些
- LeetCode-N-Queens
- Python中的装饰器和函数式
- 安装SDK只需两步---超简单!
- iOS初学者联盟之UILabel基础属性大全
- Java实现二叉树重构
- 阿里巴巴校招
- hdu5410 CRB and His Birthday
- uva 11995
- wince6.0 自己编译BSP 支持sqlCE3.0