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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
public class Solution {
public List<String[]> solveNQueens(int n) {
List<String[]> res = new ArrayList<String[]>();
solve(0, n, new int[n], res);
return res;
}
private void solve(int i, int n, int[] positions,
List<String[]> list) {
if (i == n) {
String[] result = new String[n];
for (int k = 0; k < n; k++) {
StringBuffer sb = new StringBuffer();
for (int j = 0; j < n; j++) {
if (j == positions[k])
sb.append('Q');
else
sb.append('.');
}
result[k] = sb.toString();
}
list.add(result);
} else {
for (int j = 0; j < n; j++) {
positions[i] = j;
if (validate(i, positions)) {
solve(i+1, n, positions, list);
}
}
}
}
private boolean validate(int maxRow, int[] positions) {
for (int i = 0; i < maxRow; i++) {
if (positions[i] == positions[maxRow]
|| Math.abs(positions[i] - positions[maxRow]) == maxRow - i)
return false;
}
return true;
}
}
本文详细阐述了N皇后问题的解决方案,通过Java实现,展示了如何使用递归和回溯法来找到所有可能的棋盘配置,每个解决方案都以独特的棋盘布局形式呈现。
3341

被折叠的 条评论
为什么被折叠?



