求解思路:在棋盘的每一行放入一个皇后,求出全排列种数,在排列过程中,每一步都去判断已经排下的棋子是否对当前放下的棋子造成攻击,如果有攻击的可能就放弃这一步
package com.hanzheng.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NQueenBoard {
private static List<Board> result;
public static void main(String[] args) {
result = new ArrayList<>();
int N = 8;
traversal(N, 0);
for (int i = 0; i < result.size(); i++) {
Board board = result.get(i);
board.print(i);
}
}
private static void traversal(int N, int row) {
Board board = new Board(N);
backtrack(board, row);
}
private static void backtrack(Board board, int row) {
if (row == board.size() - 1) {
result.add(Board.copy(board));
return;
}
for (int col = 0; col < board.size(); col++) {
if (hasAttackRisk(row, col, board)) {
continue;
}
// 选择放置皇后
board.set(row, col, "Q");
backtrack(board, row + 1);
// 撤销
board.set(row, col, "#");
}
}
private static boolean hasAttackRisk(int row, int col, Board board) {
String[][] boardMap = board.get();
int N = board.size();
// 检查同一列上是否有皇后
for (int i = 0; i < N; i++) {
if ("Q".equals(boardMap[i][col])) {
return true;
}
}
// 检查右上对角线是否有皇后
for (int i = row - 1, j = col + 1; i >= 0 && j < N; i--, j++) {
if ("Q".equals(boardMap[i][j])) {
return true;
}
}
// 检查左上对角线是否有皇后
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if ("Q".equals(boardMap[i][j])) {
return true;
}
}
return false;
}
static class Board {
private final String[][] board;
public Board(int N) {
board = new String[N][N];
for (int row = 0; row < board.length; row++) {
Arrays.fill(board[row], "#");
}
}
public static Board copy(Board board) {
Board copy = new Board(board.size());
String[][] map = board.get();
for (int row = 0; row < map.length; row++) {
for (int col = 0; col < map[row].length; col++) {
copy.set(row, col, map[row][col]);
}
}
return copy;
}
public int size() {
return board.length;
}
public void set(int row, int col, String queen) {
board[row][col] = queen;
}
public String[][] get() {
return board;
}
public void print(int n) {
System.out.println("第" + n + "种解法:");
for (int i = 0; i < board.length; i++) {
StringBuffer sb = new StringBuffer();
for (int j = 0; j < board.length; j++) {
sb.append(board[i][j]).append(" ");
}
System.out.println(sb);
}
}
}
}