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.

Example:

Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
 

注意:任意斜线也不能有两个Q

class Solution {
public List<List<String>> solveNQueens(int n) {
List<String> ans = new ArrayList<String>();
//initialize ans
for(int i = 0; i < n; i++){
StringBuilder s = new StringBuilder();
for(int j = 0; j < n; j++){
s.append(".");
}
ans.add(s.toString());
} dfs(n,0,ans);
return ret;
} public void dfs(int n, int depth, List<String> ans){ if(depth == n) {
List<String> new_ans = new ArrayList<String>(ans);
ret.add(new_ans);
return;
}
StringBuilder strBuilder = new StringBuilder(ans.get(depth));
for(int i = 0; i < n; i++){
if(check(n, ans, depth, i)) continue; //already have Q in this column strBuilder.setCharAt(i, 'Q');
ans.set(depth, strBuilder.toString());
dfs(n, depth+1, ans);
strBuilder.setCharAt(i, '.'); //recover
ans.set(depth, strBuilder.toString());
}
} public Boolean check(int n, List<String> ans, int i, int j){
for(int k = 0; k < i; k++){ //iterate n line
//i-k = j-x => x = j+k-i; i-k = x-j => x = i+j-k
if( ans.get(k).charAt(j) == 'Q'
||(j+k-i >= 0 && ans.get(k).charAt(j+k-i) == 'Q')
|| (i+j-k < n && ans.get(k).charAt(i+j-k) == 'Q'))
return true;
} return false;
} private List<List<String>> ret = new ArrayList<>();
}

51. N-Queens (JAVA)的更多相关文章

  1. CXF错误:Unsupported major.minor version 51.0,java.lang.UnsupportedClassVersionErro

    CXF错误:Unsupported major.minor version 51.0 java.lang.UnsupportedClassVersionError >>>>&g ...

  2. 第51章:Java操作MongoDB-[Mongo-Java-2.x]

    ①范例:连接数据库 package cn.mldn.demo; import com.mongodb.DB; import com.mongodb.MongoClient; public class ...

  3. 第51节:Java当中的集合框架Map

    简书作者:达叔小生 Java当中的集合框架Map 01 Map提供了三个集合视图: 键集 值集 键-值 映射集 public String getWeek(int num){ if(num<0 ...

  4. java.lang.UnsupportedClassVersionError: org/apache/maven/cli/MavenCli : Unsupported major.minor version 51

    http://blog.csdn.net/e_wsq/article/details/52100234 一日换了一下MyEclipse,换成2016CI,结果从SVN上下载了一个工程后出现以下错误: ...

  5. java.lang.UnsupportedClassVersionError: org/openqa/selenium/WebDriver : Unsupported major.minor version 51.0

    周一上班,正常打开myeclipse,随便写了一个main方法执行.发现报错了... 问题提示如下: java.lang.UnsupportedClassVersionError: org/openq ...

  6. Java运行 Unsupported major.minor version 51.0 错误

    今天写了简单的Java程序,运行的时候不知道为啥出现这个问题 happy@happy-HP-Compaq-dx7518-MT:~/Study/CrazyJava$ java FieldTest Exc ...

  7. 记一次jdk升级引起的 Unsupported major.minor version 51.0

    之前jdk 一直是1.6,tomcat 是6.x 版本,, 现在引入的新的jar, 出现 Caused by: java.lang.UnsupportedClassVersionError: org/ ...

  8. myeclipse 无法启动 java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).

    把myeclipse10 按照目录完整拷贝到了另外一台电脑, 另外的目录 原安装目录 D\:\soft\i\myeclipse10 新安装目录 E\:\soft\myeclipse10 双击启动失败, ...

  9. 【java.lang.UnsupportedClassVersionError】版本不一致出错

    这种错误的全部报错信息: java.lang.UnsupportedClassVersionError: org/apache/lucene/store/Directory : Unsupported ...

  10. 为何JAVA虚函数(虚方法)会造成父类可以"访问"子类的假象?

      首先,来看一个简单的JAVA类,Base. 1 public class Base { 2 String str = "Base string"; 3 protected vo ...

随机推荐

  1. Runtime 源码阅读

    Runtime 属性说明 /** * 每一个 Java 应用程序都有一个关联的运行时对象 * * @author unascribed * @see java.lang.Runtime#getRunt ...

  2. LC 959. Regions Cut By Slashes

    In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space.  Th ...

  3. js常用遍历汇总

    1, for(let i of Array) for( let i of arr){ console.log(i); } ES6新增的,i代表每次循环Array的值,相当于Array[0]到Array ...

  4. JAVA和Tomcat运维整理

    安装JAVA和Tomcatapache-tomcat-8.5.37.tar.gz  jdk-8u191-linux-x64.rpm [root@localhost ~]# ll /usr/java/t ...

  5. 利用Calendar类判断是平年还是闰年

    package com.bgs.Math; import java.util.Calendar; import java.util.Scanner; /*###14.21_常见对象(如何获取任意年份是 ...

  6. C#中的datatable类型作为参数传入SQL的存储空间

    SQL中首先建立一个结构一样的自定义类型的表格,在存储空间中申明一个此类型的变量,此处注意此时后面必须有readonly,如: @paravalue_insert MaterialStruct rea ...

  7. SqlServer:SqlServer(存储过程动态表查询(取消返回值),事务处理,批量还原sqlserver备份,强制删除被占用的数据库)

    1.存储过程动态表查询 USE [NETWORKING_AUDIT] GO /****** Object: StoredProcedure [dbo].[impConfigInfo] Script D ...

  8. MVC模型简介

    MVC模型:是一种架构型的模式,本身不引入新功能,只是帮助我们将开发的结构组织的更加合理,使展示与模型分离.流程控制逻辑.业务逻辑调用与展示逻辑分离. 首先让我们了解下MVC(Model-View-C ...

  9. 手写k-means算法

    作为聚类的代表算法,k-means本属于NP难问题,通过迭代优化的方式,可以求解出近似解. 伪代码如下: 1,算法部分 距离采用欧氏距离.参数默认值随意选的. import numpy as np d ...

  10. XXE漏洞简析

    0x00.什么是XXE? XML外部实体注入(XML External Entity Injection) XML基础 XML用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型. ...