import java.util.ArrayList;
import java.util.List;
public class Solution {
public static int[][] chessboard = new int[8][8];
public static List<String> solutionStrs = new ArrayList<>(); //每行的皇后列位置
public static void findQueenPosition(int row) {
if (row >= 8) {
addSolution();
return;
}
for (int col = 0; col < 8; col++) {
if (isValid(row, col)) {
chessboard[row][col] = 1;
findQueenPosition(row + 1);
chessboard[row][col] = 0;
}
}
}
public static boolean isValid(int row, int col) {
for (int i = 0; i < row; i++) {
if (chessboard[i][col] == 1) {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chessboard[i][j] == 1) {
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j <= 7; i--, j++) {
if (chessboard[i][j] == 1) {
return false;
}
}
return true;
}
public static void addSolution() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (chessboard[i][j] == 1) {
builder.append("col:").append(j).append(",");
}
}
}
solutionStrs.add(builder.toString());
}
public static String getChessboardTableFormat() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (chessboard[i][j] == 1) {
builder.append("o ");
} else {
builder.append("+ ");
}
}
builder.append("\n");
}
builder.append("\n");
return builder.toString();
}
public static void main(String[] args) {
//开始寻找第0行皇后所在列的位置
findQueenPosition(0);
System.out.println("八皇后问题有 " + solutionStrs.size() + " 种解法");
}
}
八皇后问题
最新推荐文章于 2023-12-16 20:42:40 发布