以下是一个用 Java 实现八皇后问题的示例代码: ```java import java.util.Arrays; public class EightQueens { // 检查当前位置是否可以放置皇后 public static boolean isSafe(int[] board, int row, int col) { // 检查同一列 for (int i = 0; i < row; i++) { if (board[i] == col) { return false; } } // 检查左上角对角线 for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (board[i] == j) { return false; } } // 检查右上角对角线 for (int i = row, j = col; i >= 0 && j < board.length; i--, j++) { if (board[i] == j) { return false; } } return true; } // 递归放置皇后 public static void solve(int[] board, int row) { if (row == board.length) { System.out.println(Arrays.toString(board)); return; } for (int col = 0; col < board.length; col++) { if (isSafe(board, row, col)) { board[row] = col; solve(board, row + 1); } } } public static void main(String[] args) { int n = 8; int[] board = new int[n]; solve(board, 0); } } ``` 对于这个八皇后问题的代码实现,您需要注意以下 3 点逻辑: 1. 对安全性的判断要全面,涵盖列、对角线等多个方向。 2. 递归过程中要正确处理回溯的情况。 3. 最终的输出格式要清晰明了,便于查看结果。 [2024-11-29 07:58:43 | AI写代码神器 | 449点数解答]