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.

解题思路:经典的八皇后问题,由于之前在《JAVA语言程序设计》中exerice6-22中做过这种问题,代码直接拿来修改下即可,JAVA实现如下:

static public List<String[]> solveNQueens(int n) {
List<String[]> list=new ArrayList<String[]>();
if(n==1){
String[] str={"Q"};
list.add(str);
return list;
}
// int count = 0;
int[] queens = new int[n]; // queens are placed at (i, queens[i])
for (int i = 0; i < n; i++)
queens[i] = -1;
queens[0] = 0;
int k = 1;
while (k >=0) {
int j = findPosition(k, queens,n);
if (j ==-1) {
queens[k] = -1;
k--; // back track to the previous row
} else {
queens[k] = j;
if (k == n-1) {
// count++;
String[] queenArray=new String[n];
for(int i=0;i<n;i++){
StringBuilder sb=new StringBuilder();
for(int j2=0;j2<n;j2++){
if(j2==queens[i])
sb.append('Q');
else sb.append('.');
}
queenArray[i]=new String(sb);
}
list.add(queenArray);
}
else {
k++;
}
}
}
return list;
}
public static int findPosition(int k, int[] queens,int n) {
int start = queens[k] == -1 ? 0 : queens[k] + 1;
for (int j = start; j < n; j++) {
if (isValid(k, j, queens,n))
return j;
}
return -1;
} public static boolean isValid(int k, int j, int queens[],int n) {
for (int i = 0; i < k; i++)
if (queens[i] == j)
return false;
for (int row = k - 1, column = j - 1; row >= 0 && column >= 0; row--, column--)
if (queens[row] == column)
return false;
for (int row = k - 1, column = j + 1; row >= 0 && column <= n-1; row--, column++)
if (queens[row] == column)
return false;
return true;
}

Java for LeetCode 051 N-Queens的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. Java for LeetCode 214 Shortest Palindrome

    Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ...

  3. Java for LeetCode 212 Word Search II

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  4. Java for LeetCode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...

  5. Java for LeetCode 210 Course Schedule II

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

  6. Java for LeetCode 200 Number of Islands

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...

  7. Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  8. Java for LeetCode 154 Find Minimum in Rotated Sorted Array II

    Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...

  9. Java for LeetCode 153 Find Minimum in Rotated Sorted Array

    Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...

随机推荐

  1. 左偏树(DP)问题

    问题:A straight dirt road connects two fields on FJ's farm, but it changes elevation more than FJ woul ...

  2. ubuntu 14.04 vim install youcompleteme

    sudo apt-get install vim ; sudo apt-get install vim-youcompleteme ; sudo apt-get install vim-addon-m ...

  3. 中国天气网-天气预报接口api

    中国天气网地址:http://www.weather.com.cn 请求服务 : 查询实时天气信息 http://www.weather.com.cn/data/sk/101110101.html 在 ...

  4. python urllib2使用心得

    python urllib2使用心得 1.http GET请求 过程:获取返回结果,关闭连接,打印结果 f = urllib2.urlopen(req, timeout=10) the_page = ...

  5. Linux下添加新硬盘,分区及挂载

    挂载好新硬盘后输入fdisk -l命令看当前磁盘信息 可以看到除了当前的第一块硬盘外还有一块sdb的第二块硬盘,然后用fdisk /dev/sdb 进行分区 进入fdisk命令,输入h可以看到该命令的 ...

  6. UIScrollview自动布局,UIScrollviewAutolayoutDemo

    参考文档:http://www.cocoachina.com/ios/20150104/10810.html UIScrollviewAutolayoutDemo地址:http://pan.baidu ...

  7. xcrun: error: active developer path ("/Volumes/Xcode/Xcode-beta.app/Contents/Developer") does not exist, use `xcode-select --swi

    xcrun: error: active developer path ("/Volumes/Xcode/Xcode-beta.app/Contents/Developer") d ...

  8. 整理时下流行的浏览器User-Agent大全

    总结整理时下流行的浏览器User-Agent大全 此文章转至:http://www.360doc.com/content/12/1012/21/7662927_241124973.shtml 用于学习 ...

  9. Linux下远程cp命令scp

    2014-2.19  PS1.在用此命令cpLinux与Linux之间的数据时发现有些服务器上默认没有安装scp但用yum -y install scp提示么有这样的包 后来发现原来scp工具的安装包 ...

  10. ThinkPHP3.2.3自带的分页用法--很简单实用

    把解压后的Page.class.php放入ThinkPHP/Extend/Library/ORG/Util/(如果没有请手动创建)目录下面.thinkphp 自带的分页非常好用美观,先看一下如下代码片 ...