将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击即使其中任意两个皇后都不同列、同行和在一条斜线上
输入:n = 4
输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
image
class Queen {
public List<List<String>> solveNQueens(int n) {
List<List<String>> solutions = new ArrayList<List<String>>();
int[] array = new int[n]; //下标代表行,其值代表列
Arrays.fill(array, -1); //初始化
Set<Integer> columns = new HashSet<Integer>();
Set<Integer> slope1s = new HashSet<Integer>();
Set<Integer> slope2s = new HashSet<Integer>();
backTrace(solutions, n, 0, columns, slope1s, slope2s, array);
return solutions;
}
public void backTrace(List<List<String>> solutions, int n, int row, Set<Integer> columns, Set<Integer> slope1s, Set<Integer> slope2s, int[] array) {
if (row == n) {
//第一组解已排列好,生成棋盘
List<String> board = generateBoard(array, n);
solutions.add(board);
} else {
for (int i = 0; i < n; i++) {
//以下几个if分别判断是否在同一列,同一右斜线,同一左斜线
if (columns.contains(i))
continue;
int slope1= row - i;
if (slope1s.contains(slope1))
continue;
int slope2= row + i;
if (slope2s.contains(slope2))
continue;
array[row] = i;
columns.add(i);
slope1s.add(slope1);
slope2s.add(slope2);
backTrace(solutions, n, row + 1, columns, slope1s, slope2s, array);
columns.remove(i);
slope1s.remove(slope1);
slope2s.remove(slope2);
}
}
}
public List<String> generateBoard(int[] array, int n) {
List<String> board = new ArrayList<String>();
for (int i = 0; i < n; i++) {
char[] row = new char[n];
Arrays.fill(row, '.');
row[array[i]] = 'Q';
board.add(new String(row));
}
return board;
}
}