51 N-Queens
来源:互联网 发布:广电直播软件 编辑:程序博客网 时间:2024/06/06 02:43
public class Solution { public List<List<String>> solveNQueens(int n) { int[]a=new int[n]; init(a); int i = 0, j = 0; List<List<String>>list=new ArrayList<List<String>>(); while (i < a.length) { while (j < a.length) { if (isValid(i, j, a)) { a[i] = j; j = 0; break; } else { j++; } } if (a[i] == -100) { // 第i行没有找到放置皇后的位置 if (i == 0) // 回溯到第一行,仍然无法找到可以放置皇后的位置,则说明已经找到所有的解,程序终止 break; else { i--; j = a[i] + 1; // 上一行皇后的位置向后移一列 a[i] = -100; // 上一行皇后的位置清除 continue; } } if (i == (a.length - 1)) { // 最后一行找到皇后位置,说明找到一个解 list.add(print(a)); j = a[i] + 1; a[i] = -100; continue; } i++; } return list; } private static void init(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = -100; } } private static boolean isValid(int row, int col, int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] == col || Math.abs(i - row) == Math.abs(a[i] - col)) { return false; } } return true; } private static List<String> print(int[] a) { List<String>res=new ArrayList<String>(); String str=""; for (int i = 0; i < a.length; i++) { str=""; for (int j = 0; j < a.length; j++) { if (a[i] != j) str+="."; else str+="Q"; } res.add(str); } return res; }}
参考N皇后问题的两个最高效的算法
0 0
- [leetcode 51] N-Queens
- LeetCode(51) N-Queens
- leetcode-51-N-Queens
- leetcode 51: N-Queens
- 51 N-Queens
- LeetCode 51: N-Queens
- LeetCode 51 - N-Queens
- Leetcode 51 N-Queens
- LeetCode 51 N-Queens
- leetcode(51):N-Queens
- LeetCode 51 N-Queens
- 51- N Queens
- FTPrep, 51 N-Queens
- Leetcode 51 N-Queens
- LeetCode 51 N-Queens II
- [leetcode-51]N-Queens(java)
- LeetCode(51) N-Queens
- LeetCode 51 - N-Queens II
- Java反射机制初涉
- HDU 杭电2501 Tiling_easy version【规律题】
- linux-fdisk/mke2fs/dumpe2fs/fsck
- 写给同事的前端学习路线<转>
- NPOI操作Excel 005:写入空Excel(Winform版)
- 51 N-Queens
- 内部存储的读操作及使用API获得路径
- 指向数组的指针
- Objective-C入门教程——Done!
- 拓扑排序
- [C++]Remove Duplicates from Sorted List 从已排序的链表中移除重复元素
- windons 下如何使用c compiler加cython 加速 word2vec!!!
- 这次带来的小程序是:确定一个字符串有多少个单词,然后最长单词和最短单词有哪些
- 通知