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

74人阅读 评论(0)

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56989次
• 积分：3213
• 等级：
• 排名：第10664名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论