第七章第三十六题(游戏:八皇后问题)(Game: Eight Queens)
-
***7.36(游戏:八皇后问题)经典的八皇后难题是要将八个皇后放在棋盘上,任何两个皇后都不能互相攻击(即没有两个皇后是在同一行、同一列或者同一个对角上)。可能的解决方案有很多。编写程序显示一个这样的解决方案。
***7.36(Game: Eight Queens)The classic problem of eight queens is to put eight queens on the chessboard, and no two Queens can attack each other (that is, no two queens are on the same line, column or opposite corner). There are many possible solutions. Write a program to show such a solution. -
参考代码:
package chapter07; public class Code_36 { // 定义一个数组 表示棋盘 public static Integer[][] checkerBoard = new Integer[8][8]; // 棋盘副本 public static Integer[][] checkerBoardCopy = new Integer[8][8]; // 计数器 用于计数有多少种方法 public static Integer jishu = 1; // 定义横竖斜方向上是否有棋子 public static boolean flag1 = true; public static boolean flag2 = true; public static boolean flag3 = true; public static boolean flag4 = true; // 初始化一个棋盘 8x8 public static void init() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { System.out.print(0 + " "); checkerBoard[i][j] = 0; } System.out.println(); } checkerBoardCopy = checkerBoard; } // 递归测试方法 public static void startTest(int row) { for (int col = 0; col < 8; col++) { if (checkCheet(row, col, checkerBoardCopy) == 1) { if (row < 7) { startTest(++row); --row; } } // 该行重新赋值为0 进行下一次判断 checkerBoardCopy[row][col] = 0; } } // 检查是否危险 // row行 // col列 public static int checkCheet(int row, int col, Integer[]