原题网址:https://leetcode.com/problems/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.."] ]
方法:深度优先搜索。
public class Solution {
private boolean valid(int[] queens, int row, int col) {
for(int r=0; r<row; r++) {
if (queens[r] == col) return false;
if (Math.abs(queens[r] - col) == Math.abs(r - row)) return false;
}
return true;
}
private void find(int n, int row, int[] queens, List<List<String>> results) {
if (row == n) {
List<String> result = new ArrayList<>();
char[] sa = new char[n];
Arrays.fill(sa, '.');
for(int i=0; i<n; i++) {
sa[queens[i]] = 'Q';
result.add(new String(sa));
sa[queens[i]] = '.';
}
results.add(result);
return;
}
for(int i=0; i<n; i++) {
if (!valid(queens, row, i)) continue;
queens[row] = i;
find(n, row+1, queens, results);
}
}
public List<List<String>> solveNQueens(int n) {
List<List<String>> results = new ArrayList<>();
find(n, 0, new int[n], results);
return results;
}
}
也可以用哈希算法来快速校验:
public class Solution {
private void find(int row, char[][] board, boolean[] cols, boolean[] diags, boolean[] adiags, List<List<String>> results) {
if (row == 0) {
for(char[] b : board) {
Arrays.fill(b, '.');
}
}
if (row == board.length) {
List<String> result = new ArrayList<>(row);
for(int i = 0; i < row; i++) {
result.add(new String(board[i]));
}
results.add(result);
return;
}
for(int i = 0; i < cols.length; i++) {
if (cols[i]) continue;
if (diags[row - i + board.length]) continue;
if (adiags[row + i]) continue;
cols[i] = true;
diags[row - i + board.length] = true;
adiags[row + i] = true;
board[row][i] = 'Q';
find(row + 1, board, cols, diags, adiags, results);
cols[i] = false;
diags[row - i + board.length] = false;
adiags[row + i] = false;
board[row][i] = '.';
}
}
public List<List<String>> solveNQueens(int n) {
List<List<String>> results = new ArrayList<>();
find(0, new char[n][n], new boolean[n], new boolean[n * 2], new boolean[n * 2], results);
return results;
}
}