皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

上图为 8 皇后问题的一种解法。

给定一个整数 n,返回所有不同的 皇后问题的解决方案。

每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

示例:

输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."], ["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。 思路:
按上述解法1queens数组为[1,3,0,2] 因为没以行就一个queens所以不用考虑行了,只纪录该行哪一列放了Q
先建立queens数组(建立好后用addSolution填好Q和point),用回溯的方法,把所有满足题意的方式都穷举出来.
TIME:O(N^N)?
SPACE:O(N)
 class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
if(n <= 0)return res; helper(res,new int[n],0);
return res;
}
public void helper(List<List<String>> res,int[] queens,int pos){
if(pos == queens.length){
addSolution(res,queens);
return;
} for(int i = 0;i < queens.length;i++){
queens[pos] = i;
if(isValid(queens,pos)){
helper(res,queens,pos+1);
}
}
}
public boolean isValid(int[] queens,int pos){
for(int i = 0;i < pos;i++){
if(queens[i] == queens[pos]){//在同一列
return false;
}else if(Math.abs(queens[pos] - queens[i]) == Math.abs(i - pos)){//在同一对角线上
return false;
}
}
return true;
}
public void addSolution(List<List<String>> res ,int[] queens){
List<String> list = new ArrayList<>();
for(int i = 0;i < queens.length;i++){
StringBuilder sb = new StringBuilder();
for(int j = 0;j < queens.length;j++){
if(queens[i] == j){
sb.append('Q');
}else{
sb.append('.');
}
}
list.add(sb.toString()); }
res.add(list);
}
}

2019-05-08 20:51:23

python版本,秒杀java

 class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def DFS(queens,xy_dif,xy_sum):
p = len(queens)
if p == n:
result.append(queens)
return None
for q in range(n):
if q not in queens and p-q not in xy_dif and p+q not in xy_sum:
DFS(queens+[q],xy_dif+[p-q],xy_sum+[p+q])
result = []
DFS([],[],[])
return [["."*i + "Q" + "."*(n-i-1) for i in sol]for sol in result]

2020-01-13 16:38:14

LeetCode--051--N皇后(java)-star的更多相关文章

  1. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  2. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  3. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  4. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  5. Java for LeetCode 051 N-Queens

    Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a d ...

  6. Java实现 LeetCode 52 N皇后 II

    52. N皇后 II n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回 n 皇后不同的解决方案 ...

  7. Java实现 LeetCode 51 N皇后

    51. N皇后 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回所有不同的 n 皇后问题的解决 ...

  8. [LeetCode] N-Queens N皇后问题

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens ...

  9. 八皇后java算法

    import java.util.Date; public class EightQueen { public static void main(String[] args) {  long star ...

  10. 极限编程,最强N皇后JAVA解题代码,4秒出15皇后,33秒出16皇后

    私人博客原文链接来自:http://www.hexcode.cn/article/show/eight-queen 8皇后以及N皇后算法探究,回溯算法的JAVA实现,非递归,循环控制及其优化 8皇后以 ...

随机推荐

  1. 源码编译apache设置系统启动失败

    文章为转载,亲试成功. Apache无法自动启动,1.将apachectl文件拷贝到/etc/rc.d/init.d 中,然后在/etc/rc.d/rc5.d/下加入链接即可.命令如下:cp /usr ...

  2. 用JS实现将十进制转化为二进制

  3. (一)Maven之使用入门

    目录 今天是端午节哦,昨天大学同学举个了会.鱼头泡饼贼拉香,嗯哼,有点跑题了:之后去了同学家里坐了坐:发现同我有一样的书,即:<maven实战>:记得是从二手网店淘到的,已经买了有小半年, ...

  4. java.lang.NoClassDefFoundError: com/opensymphony/xwork2/util/finder/DefaultClassFinder$InfoBuildingV 解决方法

    问题:严重: Unable to read class [com.spml.action.AddUserAction]java.lang.NoClassDefFoundError: com/opens ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第4节 ArrayList集合_18-练习三_按指定格式打印集合的方法

    主要锻炼用集合作为参数 使用if判断语句

  6. 多线程threading初识,线程等待

    1.线程是程序里面最小的执行单元. 2.进程是资源的集合. 线程是包含在进程里面的,一个进程可以有多个线程,但只要要有一个线程. 一.多线程,就是N个线程一起干活: 1.传统方式,串行,循环5次需要1 ...

  7. elasticsearch数据基于snapshot的还原备份+版本升级

    前言 之前安装的是elasticsearch-6.5.0,漏洞扫描报The remote web server hosts a Java application that is vulnerable. ...

  8. Vuex模块:不开启命名空间

    模块不开启命名空间时,会共享全局命名空间. { state: { 模块1: "局部状态1", 模块2: "局部状态2" }, getters: { getter ...

  9. python接口自动化:响应内容中json字符串对象的处理

    实现代码如下: import json #定义一个字典.一个列表.两个字符串({}中必须是双引号) di1={"} di2=[{"}] di3='{"name" ...

  10. git_03_git可视化工具github Desktop使用教程

    前言 github desktop是github的桌面客户端,支持Windows和Mac OS版本.使用简单,可以查看.切换和创建分支,以及提交.合并或部署代码. 下载 由于电脑限制,这里以mac o ...