51.N-Queens
The n-queens puzzle is the problem of placing n
queens on an n x n
chessboard such that no two queens attack each other.
Given an integer n
, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space, respectively.
Example 1:

Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1 Output: [["Q"]]
public static List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
int[] queenList = new int[n]; //第i个位置存放的数表示row行时,Q的列,如果queenList[0] = 2,表示第0行的第二列是Q
placeQueen(queenList, 0, n, res);//在第0行放Q
return res;
}
private static void placeQueen(int[] queenList, int row, int n, List<List<String>> res) {
//如果已经填满,就生成结果
if (row == n) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
String str = "";
for (int col = 0; col < n; col++){
if(queenList[i] == col) {
str += "Q";
} else {
str += ".";
}
}
list.add(str);
}
res.add(list);
}
for (int col = 0; col < n; col++) {//循环每一列
if (isValid(queenList, row, col)) { //如果在该列放入Q不冲突的话
queenList[row] = col;
placeQueen(queenList, row + 1, n, res);
}
}
}
private static boolean isValid(int[] queenList, int row, int col) {
for (int i = 0; i < row; i++) {
int pos = queenList[i];
if (pos == col) { //和新加入的Q处于同一列
return false;
}
if (pos + row - i == col) { //在新加入的Q的右对角线上
return false;
}
if (pos - row + i == col) { //在新加入的Q的左对角线上
return false;
}
}
return true;
}
分类:
leetCode hot 100
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix