leetcode解题方案--051--N-Queens
来源:互联网 发布:mac系统的ipa文件 编辑:程序博客网 时间:2024/05/19 19:57
题目
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..”]
]
分析
递归?或者叫回溯
就是不断的试啊,有条件不符合的就返回
class Solution { public static List<List<String>> solveNQueens(int n) { List<List<String>> ret = new LinkedList<>(); boolean[] used = new boolean[n]; LinkedList<String> list = new LinkedList<>(); HashSet<Integer> diff = new HashSet<>(2*n-1); HashSet<Integer> sum = new HashSet<>(2*n-1); calculate(ret, list, n, used, -65535, diff, sum); return ret; } public static void calculate(List<List<String>> ret, List<String> list, int n, boolean[] used, int lastIndex, HashSet diff, HashSet sum) { if (list.size() == n) { ret.add(list); } for (int i = 0; i<n;i++) { if (!used[i] && i!=lastIndex-1 && i!=lastIndex+1&&!diff.contains(list.size()-i) && !sum.contains(list.size()+i)) { LinkedList<String> listtmp = new LinkedList<>(); listtmp.addAll(list); used[i] = true; diff.add(list.size() - i); sum.add(list.size()+i); StringBuffer str = new StringBuffer(""); for (int j = 0; j<n;j++) { if (j == i) { str.append("Q"); } else { str.append("."); } } listtmp.add(str.toString()); calculate(ret, listtmp, n, used,i,diff, sum); used[i] = false; diff.remove(list.size()-i); sum.remove(list.size()+i); } } }}
阅读全文
0 0
- leetcode解题方案--051--N-Queens
- leetcode解题方案--052-- N-Queens II
- N-Queens [Leetcode解题报告]
- [leetcode javascript解题]N-Queens
- LeetCode 051 N-Queens
- LeetCode 051 N-Queens
- [leetcode] 52. N-Queens II 解题报告
- LeetCode 52. N-Queens II 解题报告
- [Leetcode] 51. N-Queens 解题报告
- [Leetcode] 52. N-Queens II 解题报告
- leetcode解题笔记 51.N-Queens [Hard]
- LeetCode: N-Queens II [051]
- leetcode之路051 N-Queens
- 【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
- poj 1200
- Android8.0 WiFi热点适配
- jQuery实现移动端左滑删除功能
- 算法爱好者——矩阵归零 ? 待解决
- 查看系统负载
- leetcode解题方案--051--N-Queens
- [洪流学堂]Hololens开发入门篇1之模拟器开发环境配置
- ZOJ Problem Set
- 数据结构上机实验任务——迷宫求解问题
- TPC/IP协议粗浅的理解
- linux回收站与自动备份文件的制作
- 页面缓存分页
- mysql主从同步
- 短信验证码URL收集