# Hard-题目18：51. N-Queens

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.

public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> list = new ArrayList<List<String>>();
backtrack(n,0,list,new boolean[n][n]);
return list;
}
private void backtrack(int n,int queens,List<List<String>> list,boolean[][] chessboard) {
if(n==queens) {
}
else {
for(int j = 0;j<n;j++) { // press a queen at chessboard[queens][j]
boolean canPress = true;
for(int s = 0;s<queens;s++) {
if(!canPress)
break;
for(int t = 0;t<n;t++) {
if(chessboard[s][t]) {
if(t==j || Math.abs(s-queens)==Math.abs(t-j)) {
canPress = false;
break;
}
}
}
}
if(canPress) {
chessboard[queens][j] = true;
backtrack(n, queens+1, list, chessboard);
chessboard[queens][j] = false;
}
}
}
}
private List<String> convert(boolean[][] chessboard,int n) {
List<String> list = new ArrayList<String>();
for(int i = 0;i<n;i++) {
String line = "";
for(int j = 0;j<n;j++) {
if(chessboard[i][j])
line+="Q";
else
line+=".";
}
}
return list;
}
}

31ms,beats 2.57%,众数6ms，19.35%
Cmershen的碎碎念：

#### LeetCode --- 51. N-Queens

2015-03-07 10:46:41

#### 【Leetcode】：51. N-Queens 问题 in JAVA

2016-04-25 19:16:59

#### LeetCode 51. N-Queens和52. N-Queens II的位运算解法

2016-09-09 17:00:08

#### LeetCode51——N-Queens

2015-10-24 20:58:58

#### [leetcode-51]N-Queens(java)

2015-08-03 09:06:27

#### 51. N-Queens Leetcode Python

2015-02-20 06:53:54

#### leetcode 51. N-Queens

2016-04-06 22:01:36

#### LeetCode 51. N-Queens--Python实现

2018-01-16 09:37:53

#### LeetCode51:N-Queens

2015-06-09 11:05:22

#### leetCode 51.N-Queens (n皇后问题) 解题思路和方法

2015-07-13 13:23:15