面试题 08.12. 八皇后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
private static final int[][] DIRECTIONS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}};

public List<List<String>> solveNQueens(int n) {
List<List<String>> resultList = new ArrayList<>();

char[][] matrix = new char[n][n];
for (char[] row : matrix) {
Arrays.fill(row, '.');
}

backtrack(resultList, matrix, 0);

return resultList;
}

private void backtrack(List<List<String>> resultList, char[][] matrix, int rowIndex) {
if (rowIndex == matrix.length) {
resultList.add(toList(matrix));
return;
}

for (int colIndex = 0; colIndex < matrix[0].length; colIndex++) {
if (canFill(matrix, rowIndex, colIndex)) {
matrix[rowIndex][colIndex] = 'Q';
backtrack(resultList, matrix, rowIndex + 1);
matrix[rowIndex][colIndex] = '.';
}
}
}

private boolean canFill(char[][] matrix, int rowIndex, int colIndex) {
int n = matrix.length;

for (int[] direction : DIRECTIONS) {
int i = rowIndex, j = colIndex;
while (i >= 0 && i < n && j >= 0 && j < n) {
if (matrix[i][j] == 'Q') {
return false;
}
i += direction[0];
j += direction[1];
}
}

return true;
}

private List<String> toList(char[][] matrix) {
List<String> list = new ArrayList<>(matrix.length);
for (char[] row : matrix) {
list.add(new String(row));
}
return list;
}
}

References

面试题 08.12. 八皇后