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. 手把手教你 iOS通过自己的服务器实现应用分发

    第一步:打包ipa 1:可以是development.ad-hoc.enterprise任何一种打包方式,导出的ipa, 稍后会将安装包上传到服务器上. 2:如下图,箭头指的要打勾 3.点击下一步后出 ...

  2. C#汉字转换拼音技术详解(高性能)

    public static class ChineseToPinYin { private static readonly Dictionary<<span class="key ...

  3. 搭建Java服务器,并且实现远程安全访问linux系统

    1.通过ssh实现安全远程访问linux系统        ssh :secure shell         加密:       1. 对称加密 (加密密钥与解密密钥相同)          des ...

  4. Dao操作的抽取

    package com.loaderman.demo.c_jdbc; public class Admin { private int id; private String userName; pri ...

  5. Redis Cluster 官方集群搭建指南

    安装ruby环境因为官方提供的创建集群的工具是用ruby写的,需要ruby2.2.2+版本支持,ruby安装需要指定openssl. 安装openssl $ wget https://www.open ...

  6. React的Sass配置

    React提供的脚手架creact-react-app创建的工程文件不像vue那种暴露出webpack来,所以添加依赖需要拐个弯. 为了配置sass需要按以下步骤进行: 一.安装sass-loader ...

  7. redis的日常操作(1)

    一.简介 [概述] redis是一种nosql数据库,他的数据是保存在内存中,同时redis可以定时把内存数据同步到磁盘,即可以将数据持久化,并且他比memcached支持更多的数据结构(string ...

  8. SQL server 自增主键重新从1开始

    原文链接:http://blog.csdn.net/zhengjia0826/article/details/43149953 dbcc checkident('sys_common_switch', ...

  9. 模拟SQLserver IO压力测试 工具编 SQLIOSIM

    描述 最近有业务需求需了解客户的服务器SQLserver 的IO情况,而不仅仅是通过系统计数器 了解硬盘的IO情况或者使用CrystalDiskMark或者Trace重播进行压力测试 .这时SQL S ...

  10. 移动端1px 边框

    伪类+ transform .border_1px:before{ content: ''; position: absolute; top: 0; height: 1px; width: 100%; ...