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. T-1-java语言基础

    一.Linux的由来和发展 Linux是开源的操作系统 Linux是服务器端的操作系统 java主要用于服务器端   二.Linux目录结构(与Windows不同) 文件系统不同:Windows是盘符 ...

  2. 82、iOS 基本算法

    “冒泡排序.选择排序.快速排序.归并排序.逆序.二分查找.求两个整数的最大公约数和最小公倍数.” 一.冒泡排序 1.比较相邻的元素.如果第一个比第二个大,就交换他们两个. 2.对每一对相邻元素作同样的 ...

  3. C#在SharePoint文档库下动态新增文件夹

    /// <summary> /// 在创建SP文库库下动态新增文件夹 /// </summary> /// <param name="spList"& ...

  4. lombok学习

    lombok的官方地址:https://projectlombok.org/ lombok的Github地址:https://github.com/rzwitserloot/lombok lombok ...

  5. spring BeanPostProcessor

    BeanPostProcessor spring使用BeanPostProcessor接口来处理生命周期的回调 BeanPostProcessor接口定义的两个方法,分别在bean的(实例化配置和初始 ...

  6. python之路(四)-set集合

    set集合 set是一个无序且不重复的元素集合优点:访问速度快,解决重复问题 l1 = [1,2,34,5,6,7,4,3,3,] s2 = set(l1) #可以以列表元祖等作为参数传进来,set集 ...

  7. android-mediaplayer播放

    优先参考 待补充.android 8.0

  8. 打造自己Django博客日记

    本教程使用的开发环境 本教程写作时开发环境的系统平台为 Windows 10 (64 位),Python 版本为 3.5.2 (64 位),Django 版本为 1.10.6. 建议尽可能地与教程的开 ...

  9. vscode调试golang环境搭建及配置

    准备VSCode 在官网下载最新版的VSCode: 安装Golang插件 打开扩展面板 VSCode->查看->扩展 找到Go插件 在搜索框里输入Go, 找到第二行写有 Rich Go l ...

  10. Lombok轮子

    前提 自从进公司实习后,项目代码中能用 Lombok 的都用了,毕竟这么好的轮子要充分利用好.也可以减少一些 get/set/toString 方法的编写,虽说 IDEA 的插件可以自动生成 get/ ...