【DFS】LeetCode 51. N 皇后
题目链接
思路
使用三个数组分别记录列、主对角线、副对角线的可放置状态。因为是按行进行搜索,在当前行放置后必进入下一行,所以不用记录行的状态。
private boolean[] mainDiagonal;
private boolean[] subDiagonal;
private boolean[] column;
判断对角线状态时可以使用小技巧。
代码
class Solution {
private List<List<String>> result;
private boolean[] mainDiagonal;
private boolean[] subDiagonal;
private boolean[] column;
private int[] board;
public List<List<String>> solveNQueens(int n) {
init(n);
dfs(n, 0);
return result;
}
private void dfs(int n, int row) {
if(row == n){
List<String> temp = new ArrayList<>();
for(int i : board){
char[] str = new char[n];
Arrays.fill(str, '.');
str[i] = 'Q';
temp.add(new String(str));
}
result.add(temp);
return;
}
for(int i = 0; i < n; i++){
if(column[i] || subDiagonal[row + i] || mainDiagonal[row - i + n - 1]){
continue;
}
board[row] = i;
column[i] = true;
mainDiagonal[row + i] = true;
subDiagonal[row - i + n - 1] = true;
dfs(n, row + 1);
column[i] = false;
mainDiagonal[row + i] = false;
subDiagonal[row - i + n - 1] = false;
}
}
private void init(int n) {
this.column = new boolean[n];
this.mainDiagonal = new boolean[2 * n - 1];
this.subDiagonal = new boolean[2 * n - 1];
this.board = new int[n];
this.result = new ArrayList<>();
}
}