# 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的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Hard-题目18：51. N-Queens 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)