import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; /**
* Source : https://oj.leetcode.com/problems/n-queens/
*
* Created by lverpeng on 2017/7/18.
*
* 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.."]
* ]
*
*/
public class NQueens { public List<String> solve (int n) {
int[][] board = new int[n][n];
List<String> result = new ArrayList<String>();
revursion(board, 0, result);
return result;
} /**
* n皇后问题,皇后所在位置的行、列、对角线都不能有其他皇后存在
* 使用递归解决
*
* @param board
* @param row
* @param result
*/
public void revursion (int[][] board, int row, List<String> result) {
if (row == board.length) {
// 找到解
StringBuilder stringBuilder = new StringBuilder();
if (result.size() > 0) {
stringBuilder.append("\n");
}
stringBuilder.append("[");
for (int i = 0; i < board.length; i++) {
stringBuilder.append("\"");
for (int j = 0; j < board.length; j++) {
if (board[i][j] == 1) {
stringBuilder.append("Q");
} else {
stringBuilder.append(".");
}
}
stringBuilder.append("\",\n");
}
stringBuilder = stringBuilder.delete(stringBuilder.length() - 3, stringBuilder.length());
stringBuilder.append("]");
result.add(stringBuilder.toString());
} for (int i = 0; i < board.length ; i++) {
if (isValiad (board, row, i)) {
board[row][i] = 1;
revursion(board, row + 1, result);
board[row][i] = 0;
}
} } private boolean isValiad (int[][] board, int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 1 || (col - row + i >= 0 && board[i][col - row + i] == 1) || (col + row - i < board.length && board[i][col + row - i] == 1)) {
return false;
}
}
return true;
} public static void main(String[] args) {
NQueens nQueens = new NQueens();
List<String> list = nQueens.solve(4);
System.out.println("=======" + list.size() + "=======");;
System.out.println(Arrays.toString(list.toArray(new String[list.size()]))); list = nQueens.solve(8);
System.out.println("=======" + list.size() + "=======");
System.out.println(Arrays.toString(list.toArray(new String[list.size()])));
} }

leetcode — n-queens的更多相关文章

  1. [Leetcode] n queens ii n皇后问题

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  2. 【LeetCode】1222. Queens That Can Attack the King 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...

  3. 【leetcode】1222. Queens That Can Attack the King

    题目如下: On an 8x8 chessboard, there can be multiple Black Queens and one White King. Given an array of ...

  4. [LeetCode] N-Queens II N皇后问题之二

    Follow up for N-Queens problem. Now, instead outputting board configurations, return the total numbe ...

  5. [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 ...

  6. [CareerCup] 9.9 Eight Queens 八皇后问题

    9.9 Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that non ...

  7. Leetcode | N-Queens I & II

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

  8. [LeetCode]题解(python):051-N-Queens

    题目来源 https://leetcode.com/problems/n-queens/ The n-queens puzzle is the problem of placing n queens ...

  9. [Leetcode][Python]52: N-Queens II

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 52: N-Queens IIhttps://oj.leetcode.com/ ...

  10. [Leetcode][Python]51: N-Queens

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 51: N-Queenshttps://oj.leetcode.com/pro ...

随机推荐

  1. adb安装apk

    1.    安装配置 1.1安装包 下载adb.zip,解压至本机 1.2环境配置 将adb安装路径加入path中 2.    安装apk 使用数据线将Android手机与电脑连接,打开手机usb调试 ...

  2. gson的特殊用法

    1.gson包在处理 字符串转 Map 或者 List 的方法. List memberList = gson.fromJson(str,new TypeToken<List>() {}. ...

  3. JAVA常用集合

    List: ArrayList: 基于动态数组的有序集合.优点:可以根据索引index下标访问List中的元素,访问速度快:缺点是访问和修改中间位置的元素时慢(数组尾部插入元素以外). LinkedL ...

  4. Java中Json字符串直接转换为对象(包括多层List集合)

    使用到的类:net.sf.json.JSONObject 使用JSON时,除了要导入JSON网站上面下载的json-lib-2.2-jdk15.jar包之外,还必须有其它几个依赖包:commons-b ...

  5. 小白Monkey学习笔记

    Monkey是google提供的一款对Android app进行压力测试工具,基于随机坐标位置,进行点击.滑动.输入等操作. Monkey的环境配置 pc电脑需要配置adb环境 Monkey程序由An ...

  6. 了解AOP

    Spring AOP的实现是基于JAVA的代理机制, 从JDK1.3开始就支持代理功能, 但是性能成为一个很大问题, 为了解决JDK代理性能问题, 出现了CGLIB代理机制.它可以生成字节码, 所以它 ...

  7. SVN完全备份,增量备份,库同步

    svn备份一般采用三种方式:1)svnadmin dump 2)svnadmin hotcopy 3)svnsync. 优缺点分析: ============== 第一种svnadmin hotcop ...

  8. Django开发目录

    Django开发[第一章]:Django基础和基本使用 Django开发[第二章]:Django URLConf 进阶 Django开发[第三章]:Django View 进阶 Django开发[第四 ...

  9. docker 1 (ubuntu docker install)

    1.移除旧内核模块 sudo apt-get remove docker \ docker-engine \ docker.io 2. 添加https传输包 sudo apt-get update s ...

  10. [转] Firewall and network filtering in libvirt

    Firewall and network filtering in libvirt There are three pieces of libvirt functionality which do n ...