一、题目描述

题目一:N 皇后问题

题目要求:分别采用随机重启爬山法、最小冲突法和遗传算法求解 n 皇后问题

题目二:Wumpus World

题目要求:使用联机搜索求解 Wumpus 怪兽世界问题

题目三:采用 α-β 剪枝算法实现井字棋游戏

题目要求:

  • 图形化界面。
  • 随机选取先手后手。
  • 可以人-计算机或计算机-计算机

    二、基本思想

    题目一:N 皇后问题

    随机重启爬山法

    随机爬山法为爬山法的一种变形,它在上山移动中随机地选择下一步;被选中的概率可能随着上山移动的陡峭程度不同而不同。这种算法通常比最陡上升算法的收敛速度慢不少,但是在某些状态空间地形图上它能找到更好的解。首选爬山法实现了随机爬山法,随机地生成后继结点直到生成一一个优于当前结点的后继。这个算法在后继结点很多的时候(例如上千个)是个好策略。
    但到随机爬山法是不完备的——它们经常会在目标存在的情况下因为被局部极大值卡住而找不到目标。随机重启爬山法( random restart hill climbing)吸纳了
    这种思想:“如果一开始没有成功,那么尝试,再尝试(重新开始搜索)”。它通过随机生成初始状态来导引爬山法搜索,直到找到目标。这个算法完备的概率接近于1。

爬山选择节点种类:

  • 简单爬山(Simple Hill climbing): 它逐个检查相邻节点,并选择第一个相邻节点作为下一个节点,优化当前开销。
    1. 评估初始状态。如果它是一个目标状态,那么停止并返回成功。否则,将初始状态设置为当前状态。
    2. 循环,直到找到解决方案状态,或者没有新的可以应用于当前状态的运算符。
      1. 选择一个尚未应用于当前状态的状态,并应用它来生成一个新状态。
      2. 执行这些操作来评估新的状态。
        1. 如果当前状态是目标状态,那么停止并返回成功。
        2. 如果它优于当前状态,那么将其设置为当前状态并进一步处理。
        3. 如果它不比当前状态好,那么继续循环,直到找到解决方案。
    3. 退出
  • 最速爬山(Steepest-Ascent Hill climbing): 它首先检查所有相邻的节点,然后选择下一个节点最接近解状态的节点。
    1. 评估初始状态。
    2. 重复这些步骤,直到找到解决方案或者当前状态不变为止。
      1. 假设“目标”为一种状态,以使当前状态的任何后继者都比它更好。
      2. 对于适用于当前状态的每个运算符
        1. 应用新的操作符并创建一个新的状态
        2. 评估新状态
        3. 如果此状态是目标状态,则退出,否则与“目标”比较
        4. 如果这个状态比“目标”要好,就把这个状态设为“目标”
        5. 如果目标优于当前状态,将当前状态设置为目标
  • 随机爬山(Stochastic hill climbing): 在决定选择哪个节点之前,它不会检查所有相邻的节点。它只是随机选择一个邻近节点,然后决定(基于该邻居的改进量)是移动到该邻居还是检查另一个邻居。


最小冲突法

最小冲突算法是一种搜索算法或启发式方法来解决约束补偿问题。为 CSP 的所有变量分配一个初始值 ,该算法会从一组变量中随机选择一个冲突违反CSP约束的变量。然后它将最小化冲突次数的值赋给这个变量。如果有一个以上具有最少数量冲突的值,则会随机选择一个。重复进行随机变量选择和最小冲突值分配的过程,直到找到解决方案或达到预选的最大迭代次数为止。因为当所有变量都有一个赋值(称为完全状态,complete state)时,CSP 可以被解释为一个局部搜索问题,所以最小冲突算法可以被看作是一个修复启发式算法,它选择冲突次数最少的状态。
尽管算法中未指定,但良好的初始分配对于快速解决问题至关重要。使用具有一定程度随机性的贪婪算法,并在其他分配均无法满足要求时允许变量分配打破约束。这种随机性有助于最小冲突避免贪婪算法初始分配创建的局部最小值。事实上,对最小冲突解决方案反应最好的约束补偿问题在贪婪算法几乎能解决问题的情况下表现得很好。

遗传算法

遗传算法(genetic algorithm, GA)是随机束搜索的一个变形,它通过把两个父状态结合来生成后继,而不是通过修改单一状态进行。这和随机剪枝搜索一样,与自然选择
类似,除了我们现在处理的是有性繁殖而不是无性繁殖。像束搜索一样,遗传算法也是从 k 个随机生成的状态开始,我们称之为种群。每个状态,或称个体,用一个有限长度的字符串表示一通常是0、1串。
遗传算法的每个状态都由它的目标函数或(用遗传算法术语)适应度函数给出评估值。对于好的状态,适应度函数应返回较高的值,所以在八皇后问题中,我们用不相互攻击的皇后对的数目来表示。并按照设置的概率随机地选择两对进行繁殖。请注意其中一个个体被选中两次而有一个一次也没被选中。对于要配对的每对个体,在字符串中随机选择一个位置作为杂交点。
像随机束搜索一样,遗传算法结合了上山趋势、随机探索和在并行搜索线程之间交换信息。遗传算法最主要的优点,如果算是,来自于杂交操作。然而可以在数学上证明,如果基因编码的位置在初始的时候就允许随机转换,杂交就没有优势了。直观上说,杂交的优势在于它能够将独立发展出来的能执行有用功能的字符区域结合起来,因此提高了搜索的粒度。例如,将前三个皇后分别放在位置2、4和6 (互不攻击)就组成了一个有用的区域,它可以和其他有用的区域组合起来形成问题的解。

题目二:Wumpus World

Wumpus World PEAS 描述:

  • 性能度量:
    • 带着金子爬出洞口 +1000
    • 掉入洞或者被Wumpus吃掉 -1000
    • 每采用一个行动得-1
    • 用掉箭 -10
    • 游戏在 Agent 死亡 或 Agent 出洞时结束。
  • 环境:

4X4的房间网格。Agent 每次都从标号为[1, 1]的方格出发,面向右方。
金子和 Wumpus 的位置按均匀分布随机选择除了起始方格以外的方格。另外,除了起始方格以外的任一方格都可能是无底洞,概率为0.2。

  • 执行器:
    • Agent 可以向前移动、左转90°或者右转90°。
    • 如果它碰上无底洞或者活着的Wumpus, 它将悲惨地死去(进入死Wumpus的方格是安全的)。
    • 如果Agent前方是一堵墙,那么不能向前移动。
    • 行动Grab可以用于捡起 Agent 所处方格内的物体。
    • 行动Shoot可以用于向 Agent 所正对的方向射箭,箭向前运动直到击中 Wumpus (此时Wumpus将被杀死)或者击中墙。Agent 只有一支箭,因此只有第一个 Shoot 行动有效。
    • 行动Climb用于爬出洞口,只能从方格[1, 1]中爬出。
  • 传感器: Agent 具有五个传感器,每个都可以提供一些单一信息,这5种感知信息以符号列表形式提供给 Agent。
    • 在Wumpus 所在之处以及与之直接相邻(非对角的)的方格内,Agent 可以感知到臭气。
    • 在与无底洞直接相邻的方格内,Agent 能感知到微风。
    • 在金子所处的方格内,Agent 感知到闪闪金光。
    • 当Agent撞到墙时,它感知到撞击。
    • 当Wumpus被杀死时,它发出的悲惨嚎叫在洞穴内的任何地方都可以感知到。

联机搜索

联机搜索问题只能通过 Agent 执行行动来求解,它不是纯粹的计算过程。
我们假设环境是确定的和完全可观察的,我们规定 Agent 只知道以下信息:

  • ACTIONS(s),返回状态s下可能进行的行动列表;单步耗散函数c(s, a, s’)——注意 Agent 知道行动的结果为状态s’时才能用;
  • GOAL-TEST(s)。

需要注意的是,Agent 并不知道 RESULT(s, a) 的值,除非 Agent 确实是在状态 s 下执行了行动 a。
在每个活动之后,联机 Agent 都能接收到感知信息,告诉它到达的当前状态;根据此信息,Agent 可以扩展自己的环境地图。可以用当前地图来决定下一步往哪里走。这种规划和活动的交替是联机搜索算法和前面讲的脱机搜索算法的不同点。另一方面,联机算法只会扩展它实际占据的结点。为了避免遍历整个搜索树去扩展下一个结点,按照局部顺序扩展结点看来更好一些。

题目三:采用 α-β 剪枝算法实现井字棋游戏

α-β 剪枝算法

α-β 剪枝可以应用于任何深度的树,很多情况下可以剪裁整个子树,而不仅仅是剪裁叶结点。一般原则是:考虑在树中某处的结点 n, 选手选择移动到该结点。如果选手在n的父结点或者更上层的任何选择点有更好的选择m,那么在实际的博弈中就永远不会到达 n。所以一旦发现关于n的足够信息(通过检查它的某些后代),能够得到上述结论,我们就可以裁剪它。
极小极大搜索是深度优先的,所以任何时候只需考虑树中某条单一路径上的结点。α-β剪枝的名称取自描述这条路径.上的回传值的两个参数:

  • α = 到目前为止路径上发现的MAX的最佳选择(即极大值)
  • β = 到目前为止路径上发现的MIN的最佳选择(即极小值)
  • α-β 搜索中不断更新 α 和 β 的值,并且当某个结点的值分别比目前的 MAX 的 α 或者 MIN 的 β 值更差的时候剪裁此结点剩下的分支(即终止递归调用)。

    三、软件设计

    3.1 需求分析

    题目一:N 皇后问题

    分别采用随机重启爬山法、最小冲突法和遗传算法求解 n 皇后问题,并对其进行不同数据规模的性能测试,分析比较不同情况下算法的性能优劣(如运行时间、运行空间等)。

    题目二:Wumpus World

    使用联机搜索求解 Wumpus 怪兽世界问题,使 Agent 尽可能获取高的分数。

    题目三:采用 α-β 剪枝算法实现井字棋游戏

    采用 α-β 剪枝算法实现井字棋游戏,要求实现如下功能:
  1. 图形化界面。
  2. 随机选取先手后手。
  3. 可以人-计算机或计算机-计算机

    3.2 总体设计

题目一:N 皇后问题

具体功能

分别实现随机重启爬山法、最小冲突法和遗传算法解决 n 皇后问题,并分析算法在不同数据规模下的性能优劣。

处理流程
  1. 程序启动,获取用户输入。
  2. 计时开始。
  3. 执行相应算法并输出执行结果。
  4. 结束计时。
  5. 输出算法运行时间。
    数据结构
  • QueenChess :存储 N 皇后的棋盘数据。
  • QueenTool:存储解决 N 皇后问题时要使用的一些基础函数。
  • HillClimbingRandomRestart:随机爬山法算法主程序。
  • MinConflictsSolver:最小冲突法主程序。
  • GeneticAlgorithm:遗传算法主程序。

题目二:Wumpus World

具体功能

使用联机搜索求解 Wumpus 怪兽世界问题

处理流程
  1. 选择游戏模式。
  2. 随机生成地图。
  3. 设置 agent 可接受死亡的概率。
  4. agent 根据所设置的逻辑进行探索并输出探索的过程,以找到金子或死亡或放弃探索结束。
  5. 输出本局游戏结果。
    数据结构
  • Agent:Agent 类,用于判断 agent 下一步如何执行。
  • Area:存储地图上的区域信息。
  • Path:查找回去的最短路径。
  • WumpusGame:游戏的交互和输出。
  • WumpusWorld:存储 Wumpus 世界的数据。


题目三:采用 α-β 剪枝算法实现井字棋游戏

具体功能

通过图形化界面实现人机对战或计算机-计算机对战,并实现计算机随机选取先后手。

处理流程
  1. 运行程序,初始化界面。
  2. 选择游戏模式。
  3. 判断游戏是否出现胜负或者平局,未出现则通过 α-β 剪枝算法,判断下一步的落子点。
  4. 游戏结束,展示游戏结果。
    数据结构
  • Algorithms: 不同算法的封装。
  • MiniMax:MiniMax 算法实现 。
  • AlphaBetaPruning:α-β 剪枝算法时间。
  • AlphaBetaAdvanced:α-β 剪枝算法优化(加入层数指标,防止递归过深)。
  • Board:棋盘数据与规则。
  • Window:可视化界面设计。

    3.3 详细设计

    题目一:N 皇后问题

    随机重启爬山法详细设计

    随机重启爬山法通过逐列遍历棋子,并将其移动到相邻的冲突减小的行来解决 N 皇后问题,当冲突值无法通过移动行减小时,则认为已经处在了局部最小值,对棋盘进行随机重启来解决问题,出于性能考虑,当移动步数大于所设定的最大步数后,程序选择退出,避免出现陷入死循环或数据量过大,程序卡死的情况。程序运行结束后,将运行结果输出给用户。

    最小冲突法函数设计

    最小冲突法通过逐列遍历棋子,并将其移动到冲突最小的行来解决 N 皇后问题,同样的,出于性能考虑,当移动步数大于所设定的最大步数后,程序选择退出,避免出现陷入死循环或数据量过大,程序卡死的情况。程序运行结束后,将运行结果输出给用户。

    遗传算法函数设计

    遗传算法通过若干随机生成棋子布局,并选择其中冲突值较少的布局,进行交叉和变异,并对子代重复上述过程直至冲突值减少为0或遗传代数超过所设最大代数。

    题目二:Wumpus World

    agent 通过已经观察到的区域,对其邻接的区域进行收益判断,选择邻接区域中死亡率最低的区域,当死亡率小于可接受范围,则移动至该区域,否则返回上一区域,发现金子则取得胜利,回到起点,若剩余未访问区域的死亡率都大于可接受范围,则放弃本局游戏。最后将游戏结果输出给用户。

    题目三:采用 α-β 剪枝算法实现井字棋游戏

    算法在 MiniMax 算法的基础上,对不必处理的分支进行剪枝处理,加快算法执行速度,同时加入了迭代深度作为参数,防止游戏层数过深,加快游戏结束速度。

    3.4 代码实现

    关键算法如下,详细算法见附件。

    题目一:N 皇后问题

  • 随机重启爬山法 ```java public class HillClimbingRandomRestart { private static int n; private static int stepsClimbedAfterLastRestart = 0; private static int totalStepsClimbed = 0; private static int heuristic = 0; private static int randomRestarts = 0; private static final int MAX_STEPS = 10000000;

    public static void main(String[] args) {

    1. n = QueenTool.getNum();
    2. long startTime = System.nanoTime();
    3. run();
    4. long endTime = System.nanoTime();
    5. System.out.println("hill climbing random restart program run time: " + (endTime - startTime) / 1000000.0 + "ms");

    }

    public static void run() {

    1. int presentHeuristic;
    2. // creating the initial Board
    3. QueenChess[] presentBoard = QueenTool.generateBoard(n);
    4. // test if the present board is the solution board
    5. presentHeuristic = QueenTool.findHeuristic(presentBoard);
    6. while ((presentHeuristic != 0) && (totalStepsClimbed < MAX_STEPS)) {
    7. // get the next board
    8. presentBoard = hillClimbing(presentBoard);
    9. presentHeuristic = heuristic;
    10. }
    11. if (totalStepsClimbed < MAX_STEPS) {
    12. //Printing the solution
    13. System.out.println("Solution to " + n + " queens using hill climbing with random restart:");
    14. QueenTool.printBoard(presentBoard);
    15. System.out.println("\nTotal number of Steps Climbed: " + totalStepsClimbed);
    16. System.out.println("Number of random restarts: " + randomRestarts);
    17. System.out.println("Steps Climbed after last restart: " + stepsClimbedAfterLastRestart);
    18. } else {
    19. System.out.println("Total Steps is bigger than max Steps!");
    20. }

    }

  1. /**
  2. * Method to get the next board with lower heuristic
  3. *
  4. * @param presentBoard p
  5. * @return lower heuristic chess board
  6. */
  7. public static QueenChess[] hillClimbing(QueenChess[] presentBoard) {
  8. QueenChess[] nextBoard = new QueenChess[n];
  9. QueenChess[] tmpBoard = new QueenChess[n];
  10. int presentHeuristic = QueenTool.findHeuristic(presentBoard);
  11. int bestHeuristic = presentHeuristic;
  12. int tempHeuristic;
  13. // Copy present board as best board and temp board
  14. for (int i = 0; i < n; i++) {
  15. nextBoard[i] = new QueenChess(presentBoard[i].getRow(), presentBoard[i].getColumn());
  16. tmpBoard[i] = nextBoard[i];
  17. }
  18. // Iterate each column
  19. for (int i = 0; i < n; i++) {
  20. // recovery the previous column and traverse the current column to find the function with the smallest heuristic value
  21. int col = (i - 1 + n) % n;
  22. tmpBoard[col] = new QueenChess(presentBoard[col].getRow(), presentBoard[col].getColumn());
  23. tmpBoard[i] = new QueenChess(0, tmpBoard[i].getColumn());
  24. // Iterate each row
  25. for (int j = 0; j < n; j++) {
  26. tempHeuristic = QueenTool.findHeuristic(tmpBoard);
  27. if (tempHeuristic < bestHeuristic) {
  28. bestHeuristic = tempHeuristic;
  29. for (int k = 0; k < n; k++) {
  30. nextBoard[k] = new QueenChess(tmpBoard[k].getRow(), tmpBoard[k].getColumn());
  31. }
  32. }
  33. //Move the queen
  34. if (tmpBoard[i].getRow() != n - 1) {
  35. tmpBoard[i].move(1, n);
  36. }
  37. }
  38. }
  39. //Check whether the present bord and the best board found have same heuristic
  40. //Then randomly generate new board and assign it to best board
  41. if (bestHeuristic == presentHeuristic) {
  42. randomRestarts++;
  43. stepsClimbedAfterLastRestart = 0;
  44. nextBoard = QueenTool.generateBoard(n);
  45. heuristic = QueenTool.findHeuristic(nextBoard);
  46. } else {
  47. heuristic = bestHeuristic;
  48. }
  49. totalStepsClimbed++;
  50. stepsClimbedAfterLastRestart++;
  51. return nextBoard;
  52. }

}

  1. - 遗传算法
  2. ```java
  3. public class GeneticAlgorithm {
  4. private static int n;
  5. private static final double MUTATE_RATE = 0.02;
  6. private static final int TIMES = 10000;
  7. public static void main(String[] args) {
  8. n = QueenTool.getNum();
  9. long startTime = System.nanoTime();
  10. run();
  11. long endTime = System.nanoTime();
  12. System.out.println("genetic algorithm program run time: " + (endTime - startTime) / 1000000.0 + "ms");
  13. }
  14. public static void run() {
  15. int[] father = init();
  16. int[] mother = init();
  17. for (int i = 0; i < TIMES; i++) {
  18. List<Integer[]> son = new ArrayList<>();
  19. for (int j = 0; j < 4 * n; j++) {
  20. son.add(Arrays.stream(crossover(father, mother)).boxed().toArray(Integer[]::new));
  21. }
  22. mutate(son);
  23. Map<Integer[], Integer> res = select(son);
  24. for (Map.Entry<Integer[], Integer> c : res.entrySet()) {
  25. if (c.getValue() == 0) {
  26. System.out.println("Solution to " + n + " queens using genetic algorithm:");
  27. QueenTool.printBoard(c.getKey());
  28. return;
  29. }
  30. }
  31. father = Arrays.stream(res.entrySet().iterator().next().getKey()).mapToInt(k -> k).toArray();
  32. mother = Arrays.stream(res.entrySet().iterator().next().getKey()).mapToInt(k -> k).toArray();
  33. }
  34. System.out.println("Generations are more than the max number of iterations!");
  35. }
  36. /**
  37. * use List to shuffle and trans to array to return
  38. *
  39. * @return a random array of the queens chess board
  40. */
  41. private static int[] init() {
  42. List<Integer> list = new ArrayList<>();
  43. for (int i = 1; i <= n; i++) {
  44. list.add(i);
  45. }
  46. Collections.shuffle(list);
  47. return list.stream().mapToInt(i -> i).toArray();
  48. }
  49. /**
  50. * Chromosomal crossover for genetic recombination
  51. *
  52. * @param originFather father of the son
  53. * @param originMother mother of the son
  54. * @return the son
  55. */
  56. private static int[] crossover(int[] originFather, int[] originMother) {
  57. int[] father = Arrays.copyOf(originFather, n);
  58. int[] mother = Arrays.copyOf(originMother, n);
  59. int[] son = new int[n];
  60. int[] rend = new int[n];
  61. for (int i = 0; i < n; i++) {
  62. rend[i] = Math.random() >= 0.5 ? 0 : 1;
  63. }
  64. int f = 0, m = 0;
  65. for (int i = 0; i < n; i++) {
  66. // move the point of chromosomal
  67. if (rend[i] == 0) {
  68. for (f = 0; f < n; f++) {
  69. if (father[f] != 0) {
  70. break;
  71. }
  72. }
  73. } else {
  74. for (m = 0; m < n; m++) {
  75. if (mother[m] != 0) {
  76. break;
  77. }
  78. }
  79. }
  80. // Inherit parents' genes
  81. son[i] = rend[i] == 0 ? father[f] : mother[m];
  82. // Set the inherited genes to 0
  83. for (int j = 0; j < n; j++) {
  84. if (father[j] == son[i]) {
  85. father[j] = 0;
  86. }
  87. if (mother[j] == son[i]) {
  88. mother[j] = 0;
  89. }
  90. }
  91. }
  92. return son;
  93. }
  94. /**
  95. * mutate to suit for the env
  96. * for the chromosome in chromosomes
  97. * choose two gene randomly to mutate
  98. *
  99. * @param chromosomes chromosomes of the obj
  100. */
  101. private static void mutate(List<Integer[]> chromosomes) {
  102. for (Integer[] chromosome : chromosomes) {
  103. if (Math.random() > MUTATE_RATE) {
  104. continue;
  105. }
  106. int i = (int) (Math.random() * n);
  107. int j = (int) (Math.random() * n);
  108. if (i == j) {
  109. continue;
  110. }
  111. // three times xor to swap two numbers to hybridize
  112. chromosome[i] ^= chromosome[j];
  113. chromosome[j] ^= chromosome[i];
  114. chromosome[i] ^= chromosome[j];
  115. }
  116. }
  117. private static Integer fit(Integer[] result) {
  118. int res = 0;
  119. for (int i = 0; i < n; i++) {
  120. for (int j = i + 1; j < n; j++) {
  121. if (Math.abs(result[i] - result[j]) == j - i || result[i].equals(result[j])) {
  122. res++;
  123. }
  124. }
  125. }
  126. return res;
  127. }
  128. /**
  129. * method to choose the best individual
  130. *
  131. * @param son subgroup of the population
  132. * @return the best individual of the subgroup
  133. */
  134. private static Map<Integer[], Integer> select(List<Integer[]> son) {
  135. Map<Integer[], Integer> result = son.stream().collect(Collectors.toMap(x -> x, GeneticAlgorithm::fit));
  136. result = result.entrySet().stream().
  137. sorted(Map.Entry.comparingByValue()).
  138. collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
  139. return result;
  140. }
  141. }
  • 最小冲突法 ```java public class MinConflictsSolver { private static int n; private static int totalStepsMoved = 0; private static final int MAX_STEPS = 100000;

    /**

    • row[i] shows the queen of the i row,col[i] shows the queen of the i col
    • mainDiag[i] shows the queen of the i main diag
    • secondaryDiag[i] shows the queen of the i secondary diag
    • Additional explanation
    • The row-col values on the diagonal from top left to bottom right are the same,use this as the index of the diag
    • Plus n - 1 to avoid the value is negative value */

      static int[] row; static int[] col; static int[] mainDiag; static int[] secondaryDiag;

      public static void main(String[] args) { n = QueenTool.getNum(); long startTime = System.nanoTime(); run(); long endTime = System.nanoTime(); System.out.println(“min conflicts program run time: “ + (endTime - startTime) / 1000000.0 + “ms”); }

      public static void run() { row = new int[n]; col = new int[n]; mainDiag = new int[2 n]; secondaryDiag = new int[2 n];

      System.out.println(“n is: “ + n); // creating the initial Board QueenChess[] board = QueenTool.generateBoard(n); update(board, row, col, mainDiag, secondaryDiag);

      int heuristic = QueenTool.findHeuristic(board); if (heuristic != 0) {

      1. minConflictsSolve(board);

      }

      if (totalStepsMoved < MAX_STEPS) {

      1. //Printing the solution
      2. System.out.println("Solution to " + n + " queens using min conflicts Solver");
      3. QueenTool.printBoard(board);
      4. System.out.println("Total number of Steps Moved: " + totalStepsMoved);

      } else {

      1. System.out.println("Total Steps is bigger than max Steps!");

      } }

      public static void minConflictsSolve(QueenChess[] board) { boolean isGood = false; while (!isGood && totalStepsMoved < MAX_STEPS) {

      1. // Iterate each column
      2. for (int i = 0; i < n; i++) {
      3. totalStepsMoved++;
      4. if (adjustRow(i, board)) {
      5. isGood = true;
      6. break;
      7. }
      8. }

      } }

      /**

    • @param column adjust row for this column
    • @return is adjust good */ public static boolean adjustRow(int column, QueenChess[] board) { // 通过列得到行 int curRow = board[column].getRow(); // 最佳行号,设置为当前行,然后更新 int bestRow = curRow;

      // row 不减一的原因是交换任然保证每行每列都有一个而已 // 现在还没移过去 // 对角线冲突数为当前对角线皇后数减一 int minConflict =

      1. row[bestRow]
      2. + mainDiag[getP(bestRow, column, n)] - 1
      3. + secondaryDiag[getC(bestRow, column)] - 1;

      // Iterate through each row for (int i = 0; i < n; i++) {

      1. if (i == curRow) {
      2. continue;
      3. }
      4. int conflict = row[i] + mainDiag[getP(i, column, n)] + secondaryDiag[getC(i, column)];
      5. // update data
      6. if (conflict < minConflict) {
      7. minConflict = conflict;
      8. bestRow = i;
      9. }

      }

      // update col, mainDiag, secondaryDiag if (bestRow != curRow) {

      1. // minus current row queen
      2. row[curRow]--;
      3. mainDiag[getP(curRow, column, n)]--;
      4. secondaryDiag[getC(curRow, column)]--;
      5. // add best row queen
      6. row[bestRow]++;
      7. mainDiag[getP(bestRow, column, n)]++;
      8. secondaryDiag[getC(bestRow, column)]++;
      9. // 注意,这里我们没有移动 在这个列上的之前的那个行上的皇后
      10. // move chess
      11. board[column].row = bestRow;
      12. // return is this col move successful
      13. if (row[curRow] == 1 && row[bestRow] == 1
      14. && mainDiag[getP(bestRow, column, n)] == 1
      15. && secondaryDiag[getC(bestRow, column)] == 1) {
      16. return satisfy(board);
      17. }

      }

      // any else return false; }

      public static boolean satisfy(QueenChess[] board) { // Iterate through each row for (int i = 0; i < n; i++) {

      1. if (row[board[i].getRow()] != 1 ||
      2. mainDiag[getP(board[i].getRow(), i, n)] != 1 ||
      3. secondaryDiag[getC(board[i].getRow(), i)] != 1) {
      4. return false;
      5. }

      } return true; }

      public static void update(QueenChess[] board, int[] row, int[] col, int[] mainDiag, int[] secondaryDiag) { int n = row.length; // 每列恰好一个皇后 // 行后续再做初始化 for (int point = 0; point < n; point++) {

      1. col[point] = 1;
      2. row[point] = 0;

      } // 初始化 diag 皇后数 for (int point = 0; point < 2 * n - 1; point++) {

      1. mainDiag[point] = 0;
      2. secondaryDiag[point] = 0;

      }

      for (int i = 0; i < n; i++) {

      1. row[board[i].getRow()]++;
      2. mainDiag[getP(board[i].getRow(), board[i].getColumn(), n)]++;
      3. secondaryDiag[getC(board[i].getRow(), board[i].getColumn())]++;

      } }

      /**

    • 给定二维矩阵的一个点坐标
    • 返回其对应的右上到左下的对角线编号 *
    • @return the index of the Diag */ public static int getP(int row, int column, int n) { return row - column + n - 1; }

      public static int getC(int row, int column) { return row + column; } }

  1. <a name="ZUmDG"></a>
  2. #### 题目二:Wumpus World
  3. ```java
  4. public class Agent {
  5. WumpusWorld world;
  6. int deathArea = 3;
  7. int unknownAreas;
  8. double acceptableRisk = 0.5;
  9. double[][] deathProbability;
  10. boolean[][] isTagged;
  11. Area agentArea;
  12. int score = 0;
  13. int steps;
  14. boolean isAgentAlive = true;
  15. boolean isGiveUp = false;
  16. boolean isWumpusAlive = true;
  17. boolean isGrabGold = false;
  18. /**
  19. * the 4 different directions of the agent at a specific time(step)
  20. */
  21. final static int NORTH = 0;
  22. final static int EAST = 1;
  23. final static int SOUTH = 2;
  24. final static int WEST = 3;
  25. String[] printDirection = {"↑", "→", "↓", "←"};
  26. /**
  27. * default direction is east
  28. */
  29. private int direction = 1;
  30. /**
  31. * init agents
  32. */
  33. public Agent(WumpusWorld wumpusWorld) {
  34. this.world = wumpusWorld;
  35. int size = world.getSize();
  36. unknownAreas = size * size;
  37. deathProbability = new double[size + 2][size + 2];
  38. isTagged = new boolean[size + 2][size + 2];
  39. agentArea = wumpusWorld.getArea(size, 1);
  40. freshDeathProbability();
  41. freshDeathProbability();
  42. markArea(agentArea);
  43. }
  44. /**
  45. * start auto playing the game
  46. */
  47. public void simulate() {
  48. if (!go(think())) {
  49. isGiveUp = true;
  50. }
  51. }
  52. // 搜寻 area 找死亡率小于可接受风险的概率的区域,未找到则放弃
  53. private int think() {
  54. int row = agentArea.getRow();
  55. int col = agentArea.getCol();
  56. double bestHeuristic = Integer.MAX_VALUE;
  57. int bestDirection = -1;
  58. if (!world.getArea(row - 1, col).getHasWall()
  59. && !world.getArea(row - 1, col).getVisited()
  60. && deathProbability[row - 1][col] < bestHeuristic) {
  61. bestHeuristic = deathProbability[row - 1][col];
  62. bestDirection = NORTH;
  63. }
  64. if (!world.getArea(row + 1, col).getHasWall()
  65. && !world.getArea(row + 1, col).getVisited()
  66. && deathProbability[row + 1][col] < bestHeuristic) {
  67. bestHeuristic = deathProbability[row + 1][col];
  68. bestDirection = SOUTH;
  69. }
  70. if (!world.getArea(row, col + 1).getHasWall()
  71. && !world.getArea(row, col + 1).getVisited()
  72. && deathProbability[row][col + 1] < bestHeuristic) {
  73. bestHeuristic = deathProbability[row][col + 1];
  74. bestDirection = EAST;
  75. }
  76. if (!world.getArea(row, col - 1).getHasWall()
  77. && !world.getArea(row, col - 1).getVisited()
  78. && deathProbability[row][col - 1] < bestHeuristic) {
  79. bestHeuristic = deathProbability[row][col - 1];
  80. bestDirection = WEST;
  81. }
  82. if (steps > world.getSize() * world.getSize() * 2.5) {
  83. isGiveUp = true;
  84. }
  85. // String pd = bestDirection == -1 ? "@" : printDirection[bestDirection];
  86. // System.out.println("deathProbability: " + bestHeuristic);
  87. // System.out.println("bestDirection: " + pd);
  88. return bestHeuristic >= acceptableRisk ? -1 : bestDirection;
  89. }
  90. public boolean go(int direction) {...}
  91. public void printWorld(boolean isKonwn) {...}
  92. public void turnLeft() {...}
  93. public void turnRight() {...}
  94. public boolean moveForward() {...}
  95. public boolean goEast() {...}
  96. public boolean goWest() {...}
  97. public boolean goNorth() {...}
  98. public boolean goSouth() {...}
  99. public boolean goBack() {...}
  100. public void markArea(Area area) {...}
  101. private void markAreaDangerous(int row, int col) {...}
  102. private void markAreaSafe(int row, int col) {...}
  103. /**
  104. * prepare to optimize the probability of hitting wumpus
  105. * undo
  106. */
  107. public void chooseDirectionToShoot() {
  108. if (isWumpusAlive()) {
  109. shootWumpus();
  110. }
  111. }
  112. public boolean shootWumpus() {...}
  113. public void grabGold() {}
  114. public boolean isAlive() {...}
  115. public boolean isGiveUp() {return isGiveUp;}
  116. public boolean isGrabGold() {return isGrabGold;}
  117. public boolean isWumpusAlive() {return isWumpusAlive;}
  118. public void wumpusScream() {...}
  119. public void setAcceptableRisk(double acceptableRisk) {this.acceptableRisk = acceptableRisk;}
  120. public void printDeathP() {...}
  121. private int updateUnknownArea(){...}
  122. public void goBackHome() {...}
  123. }

题目三:采用 α-β 剪枝算法实现井字棋游戏

  1. class AlphaBetaAdvanced {
  2. private static double maxDepth;
  3. /**
  4. * AlphaBetaAdvanced cannot be instantiated.
  5. */
  6. private AlphaBetaAdvanced() {
  7. }
  8. /**
  9. * Execute the algorithm.
  10. *
  11. * @param player the player that the AI will identify as
  12. * @param board the Tic Tac Toe board to play on
  13. * @param maxDepth the maximum depth
  14. */
  15. static void run(Board.State player, Board board, double maxDepth) {
  16. if (maxDepth < 1) {
  17. throw new IllegalArgumentException("Maximum depth must be greater than 0.");
  18. }
  19. AlphaBetaAdvanced.maxDepth = maxDepth;
  20. alphaBetaPruning(player, board, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 0);
  21. }
  22. /**
  23. * The meat of the algorithm.
  24. *
  25. * @param player the player that the AI will identify as
  26. * @param board the Tic Tac Toe board to play on
  27. * @param alpha the alpha value
  28. * @param beta the beta value
  29. * @param currentDepth the current depth
  30. * @return the score of the board
  31. */
  32. private static int alphaBetaPruning(Board.State player, Board board, double alpha, double beta, int currentDepth) {
  33. if (currentDepth++ == maxDepth || board.isGameOver()) {
  34. return score(player, board, currentDepth);
  35. }
  36. if (board.getTurn() == player) {
  37. return getMax(player, board, alpha, beta, currentDepth);
  38. } else {
  39. return getMin(player, board, alpha, beta, currentDepth);
  40. }
  41. }
  42. /**
  43. * Play the move with the highest score.
  44. *
  45. * @param player the player that the AI will identify as
  46. * @param board the Tic Tac Toe board to play on
  47. * @param alpha the alpha value
  48. * @param beta the beta value
  49. * @param currentDepth the current depth
  50. * @return the score of the board
  51. */
  52. private static int getMax(Board.State player, Board board, double alpha, double beta, int currentDepth) {
  53. int indexOfBestMove = -1;
  54. for (Integer theMove : board.getAvailableMoves()) {
  55. Board modifiedBoard = board.getDeepCopy();
  56. modifiedBoard.move(theMove);
  57. int score = alphaBetaPruning(player, modifiedBoard, alpha, beta, currentDepth);
  58. if (score > alpha) {
  59. alpha = score;
  60. indexOfBestMove = theMove;
  61. }
  62. if (alpha >= beta) {
  63. break;
  64. }
  65. }
  66. if (indexOfBestMove != -1) {
  67. board.move(indexOfBestMove);
  68. }
  69. return (int) alpha;
  70. }
  71. /**
  72. * Play the move with the lowest score.
  73. *
  74. * @param player the player that the AI will identify as
  75. * @param board the Tic Tac Toe board to play on
  76. * @param alpha the alpha value
  77. * @param beta the beta value
  78. * @param currentDepth the current depth
  79. * @return the score of the board
  80. */
  81. private static int getMin(Board.State player, Board board, double alpha, double beta, int currentDepth) {
  82. int indexOfBestMove = -1;
  83. for (Integer theMove : board.getAvailableMoves()) {
  84. Board modifiedBoard = board.getDeepCopy();
  85. modifiedBoard.move(theMove);
  86. int score = alphaBetaPruning(player, modifiedBoard, alpha, beta, currentDepth);
  87. if (score < beta) {
  88. beta = score;
  89. indexOfBestMove = theMove;
  90. }
  91. if (alpha >= beta) {
  92. break;
  93. }
  94. }
  95. if (indexOfBestMove != -1) {
  96. board.move(indexOfBestMove);
  97. }
  98. return (int) beta;
  99. }
  100. /**
  101. * Get the score of the board. Takes depth into account.
  102. *
  103. * @param player the play that the AI will identify as
  104. * @param board the Tic Tac Toe board to play on
  105. * @param currentPly the current depth
  106. * @return the score of the board
  107. */
  108. private static int score(Board.State player, Board board, int currentPly) {
  109. if (player == Board.State.Blank) {
  110. throw new IllegalArgumentException("Player must be X or O.");
  111. }
  112. Board.State opponent = (player == Board.State.X) ? Board.State.O : Board.State.X;
  113. if (board.isGameOver() && board.getWinner() == player) {
  114. return 10 - currentPly;
  115. } else if (board.isGameOver() && board.getWinner() == opponent) {
  116. return -10 + currentPly;
  117. } else {
  118. return 0;
  119. }
  120. }
  121. }

3.5 测试

运行环境

  • Windows 10 2004 64位 或更新版本
  • Java Runtime Environment 8.0 及以上

    测试结果

    所有程序进行了验收测试和易用性测试,均表现良好。

  • 题目一:N 皇后问题

随机重启爬山法、最小冲突法和遗传算法均能解决 N 皇后问题,但随机重启爬山法和遗传算法解决速度较慢。

  • 题目二:Wumpus World

agent 可以在游戏中取得平均260以上的分数,即超过 1/4 以上取得胜利。

  • 题目三:采用 α-β 剪枝算法实现井字棋游戏

α-β 剪枝算法可以达到人机对战中机器不会失落败,即机器只会出现胜利和平局两种情况。

四、运行结果及分析

题目一:N 皇后问题

随机重启爬山法、最小冲突法和遗传算法分别在 n = 10、n = 50、 n = 100、 n = 1000的运行时间如下表所示:

算法/数据规模 n = 10 n = 50 n = 100 n = 1000
随机重启爬山法 8.1840ms 3703.4996ms NaN NaN
最小冲突法 5.4067ms 7.1119ms 7.9116ms 27.0772ms
遗传算法 313.9565ms 9051.1581ms 71101.8417ms NaN

通过上表可以看出,最小冲突法是解决 N 皇后最快的方法,且运行时间基本不受数据规模的影响,相比之下,随机重启爬山法随着数据规模的提升,运行时间迅速上升,在 n = 100 时短时间内已经无法获得问题的解。
遗传算法速度较最小冲突法较慢,但比随机重启爬山法要好一点,但是遗传算法在 n 取值较小时运行时间同样较慢。

题目二:Wumpus World

wumpus world 在随机初始世界并运行 10000 次后,得到的数据如下:

  • score: 268.0
  • win times: 2791
  • failed times: 0
  • give up times: 7209

从数据可以看出, agent 采取了保守的策略,即放弃探索收益较低(死亡率高)的区域,在这样的策略下,agent 获取了平均 260 以上的成绩。

程序详细运行结果如下:

  • 启动后,初始化地图及 agent 界面和 agent 判断的每个区域的死亡概率。

image.png

  • 感受到臭味,射箭

image.png

  • 捡到金子获胜

image.png

题目三:采用 α-β 剪枝算法实现井字棋游戏

  • 程序启动并在左上角选择人机模式

image.png

  • 几局人机对战示例 (均为人(O)先手)

image.pngimage.pngimage.png

五、使用说明

  • 推荐运行环境:
    • Windows 10 64位系统
    • 安装有 Java Runtime Environment 8.0 及以上
  • 根据程序提示进行相应操作即可。

    六、小结

    题目一:N 皇后问题

    验收测试时,本应性能表现最好且基本不受 N 大小影响的最小冲突法在 N=1000时却无法在有效时间内得到运行结果,经过 JProfiler 进行性能分析,发现查找冲突数的函数调用次数最多,经过分析原来简单实现的最小冲突法会在每次可能的调整都进行冲突次数查找,并且简单实现的冲突次数也要访问整个棋盘(n^2),所以导致算法性能表现极差,随后根据一篇博客,将查找冲突数的函数由 n^2 复杂度优化到线性复杂度,同时也优化了调用查找冲突的次数。代码修改后可以看出随机重启爬山法、最小冲突法和遗传算法中最小冲突法的性能表现最好,且基本不受 N 大小的影响。

    题目二:Wumpus World

    Wumpus World 问题选择使用死亡概率作为启发值来判断移动到相邻的具体区域或选择返回,考虑到游戏目标是获取尽可能高的分数,而死亡失去的分数和得到金子后获取的分数是相等的,所以 agent 采取了保守的策略,尽量避免死亡,在测试中可以做到平均分约有260+分(10000 次测试)。

    题目三:采用 α-β 剪枝算法实现井字棋游戏

    α-β 剪枝算法在 MiniMax 算法的基础上改进,并且又加入了层数进行优化,减少算法的运行时间同时也防止对局进行过长的时间。算法可以实现 AI 在下棋时立于不败之地。

    七、参考文献

    [1] Norvig P . Artificial Intelligence: A Modern Approach, 4rd Edition[M].Pearson, 2020.
    [2] Tanvir Sojal.Computing number of conflicting pairs in N-Queen board in Linear Time and Space Complexity[EB/OL].https://towardsdatascience.com/computing-number-of-conflicting-pairs-in-a-n-queen-board-in-linear-time-and-space-complexity-e9554c0e0645,2018-11-28.