LeetCode N-Queens
来源:互联网 发布:好看的域名 编辑:程序博客网 时间:2024/06/06 12:29
原题链接在此:https://leetcode.com/problems/n-queens/
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.."]]
这是一道典型的NP问题,基本思路如下就是递归加回溯:
用递归处理子问题,当某一个子问题出错时就回溯到上一层。这类问题的时间复杂度都是指数量级的。
在子问题中,列出一种例子,判断当前情况是否合法,如果不合法就回到上一层,如果合法就DFS到下一层,当填满后就保存此正确结果。然后去掉最后添加的数,列举其他方法。但本题中不需要去掉就是因为此题是用一个一维数组代表棋盘,每个index代表行, value 代表列。
[2,0,1,3] 代表[0,2],[1,0],[2,1],[3,3]上有皇后。
但有几个问题需要注意,首先要注意返回类型是List<List<String>>,也就是List of List,在生成时一定要这么写
List<List<String>> res = new ArrayList<List<String>>();否则会报错。
其次注意declare helper function 时,argument 要写成
List<List<String>> res
还有就是用到了新的class StringBuilder, 其sb.append("Hello!")和sb.toString()非常好用。
AC Java:
</pre><pre name="code" class="java">public class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> res = new ArrayList<List<String>>(); helper(n,0,new int[n],res); return res; } private void helper(int n, int cur, int[] row, List<List<String>> res){ //cur stands for current row index if(cur == n){ List<String> temp = new ArrayList<>(); for(int j = 0; j<row.length;j++){ StringBuilder sb = new StringBuilder(); for(int i = 0; i<row.length; i++){ if(row[j] != i) { sb.append("."); }else{ sb.append("Q"); } } temp.add(sb.toString()); } res.add(temp); return; } //If we haven't reached the end for(int i = 0; i < n; i++){ row[cur] = i; if(isValid(cur, row)){ helper(n,cur+1,row,res); } } } //Check if the current queens position is valid private boolean isValid(int cur, int[] row){ for(int i = 0;i<cur;i++){ if(row[cur] == row[i] || Math.abs(row[i]-row[cur]) == (cur-i)){ return false; } } return true; }}
- 【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
- 搭建cocos2d-x-android环境 Windows XP3 + Eclipse + NDKR7(或ndkr7b)+COCOS2DX(没有用到cygwin和minigw)
- Android-NDK编译
- 用Cmake写Makefile
- wordpress插件
- Eclipse卸载android开发环境(ADT)
- LeetCode N-Queens
- Linux/Unix 学习笔记 1
- Zabbix,Nagios,OneAPM Servers 安装部署大比拼
- 游戏引擎网络开发者的 64 做与不做 | Part 1 | 客户端方面
- 7 天玩转 ASP.NET MVC — 第 2 天
- 基于天然概率的无需人为平衡的skiplist的美之展现
- Creo二次开发—内存处理
- Cocos2d-x中关于schedule函数的一点理解
- unity3d 几种镜头畸变