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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]Java代码:
public class Solution {
private int[] column;
private int[] rup;
private int[] lup;
private int[] queen;
private List<String[]> result_list;
public List<String[]> solveNQueens(int n) {
Init(n);
backtrack(1, n);
return result_list;
}
public void Init(int n) {
column = new int[n + 1];
rup = new int[(2 * n) + 1];
lup = new int[(2 * n) + 1];
for (int i = 1; i <= n; i++)
column[i] = 1;
for (int i = 1; i <= (2 * n); i++)
rup[i] = lup[i] = 1;
queen = new int[n + 1];
result_list = new ArrayList<String[]>();
}
public void backtrack(int i, int num) {
if (i > num) {
String[] result = getStringArray(num);
result_list.add(result);
} else {
for (int j = 1; j <= num; j++) {
if ((column[j] == 1) && (rup[i + j] == 1)
&& (lup[i - j + num] == 1)) {
queen[i] = j;
// 设定为占用
column[j] = rup[i + j] = lup[i - j + num] = 0;
backtrack(i + 1, num);
column[j] = rup[i + j] = lup[i - j + num] = 1;
}
}
}
}
public String[] getStringArray(int num) {
String[] result = new String[num];
StringBuilder sb = new StringBuilder();
for (int y = 1; y <= num; y++) {
for (int x = 1; x <= num; x++) {
if (queen[y] == x) {
sb.append("Q");
} else {
sb.append(".");
}
}
result[y - 1] = sb.toString();
sb.setLength(0);
}
return result;
}
}