当前位置:   article > 正文

基于Python的A*算法解决八数码问题_实验一 a*算法之八数码问题 python

实验一 a*算法之八数码问题 python

目录

一、问题描述

二、涉及算法

三、实现步骤

1.定义状态结点的类

 2.定义曼哈顿距离计算函数

3.预留占位函数

4.生成子结点函数

5.定义输出路径函数

6.定义A*算法

7.读取数据作为原始状态

8.定义主函数查看结果

四、运行结果

五、完整代码


一、问题描述

八数码问题是人工智能领域一个经典的问题。也是我们所熟悉的最简单的3×3数字华容道游戏:在一个3×3的九宫格棋盘上,摆有8个正方形方块,每一个方块都标有1~8中的某一个数字。棋盘中留有一个空格,要求按照每次只能将与空格相邻的方块与空格交换的原则,将任意摆放的数码盘(初始状态)逐步摆成某种给定的数码盘的排列方式(目标状态)。

二、涉及算法

启发式搜索又称为有信息搜索,是利用问题拥有启发信息引导搜索,以达到减小搜索范围、降低问题复杂度的目的。在启发式搜索过程中,要对Open表进行排序,这就要有一种方法来计算待扩展结点有希望通向目标结点的不同程度,人们总是希望找到最有可能通向目标结点的待扩展结点优先扩展。一种最常用的方法是定义一个评价函数对各个结点进行计算,其目的就是用来估算出“有希望”的结点。用f来标记评价函数,用f(n)表示结点n的评价函数值,并用f来排列等待扩展的结点,然后选择具有最小f值的结点作为下一个要扩展的结点。

A*算法是一种有序搜索算法,其特点在于对评价函数的定义上。这个评估函数f使得在任意结点上其函数值f(n)能估算出结点S到结点n的最小代价路径的代价与从节点n到某一目标节点的最小代价路径的代价的总和,也就是说f(n)是约束通过结点n的一条最小代价路径的代价的估计。
算法具体内容见文献:

https://wenku.baidu.com/view/4a80a40fa2161479171128de?_wkts_=1713600420821

三、实现步骤

在运行前,需要提前准备好infile.txt文件,第一行规定N的大小,即棋盘的大小,第二行则放置起始状态棋盘中的数字排列,从上往下,从左往右一次排成一列,空格置为0。

1.定义状态结点的类

定义一个State类,主要用于表示搜索过程中的状态结点,包括结点的代价和状态信息,以及结点之间的关系。

属性:

gn:从起始结点到当前结点的实际代价。

hn:从当前结点到目标结点的估计代价(启发式函数)。

fn:综合代价,即gn+hn。

child:子结点列表,存储从当前结点可以到达的所有子结点。

par:父结点,指向生成当前结点的父结点。

state:当前结点的状态矩阵。

hash_value:当前结点状态矩阵的哈希值,用于在查找表中快速查找。

方法:

__lt__:小于运算符重载,用于结点比较。

__eq__:等于运算符重载,用于结点比较。

__ne__:不等于运算符重载,用于结点比较。

  1. class State(object):
  2. def __init__(self, gn=0, hn=0, state=None, hash_value=None, par=None):
  3. self.gn = gn
  4. self.hn = hn
  5. self.fn = self.gn + self.hn
  6. self.child = []
  7. self.par = par
  8. self.state = state
  9. self.hash_value = hash_value
  10. def __lt__(self, other):
  11. return self.fn < other.fn
  12. def __eq__(self, other):
  13. return self.hash_value == other.hash_value
  14. def __ne__(self, other):
  15. return not self.__eq__(other)

 2.定义曼哈顿距离计算函数

计算两个状态结点之间的曼哈顿距离,作为启发式函数的一部分,用于评估当前结点到目标结点的估计代价。

  1. def manhattan_dis(cur_node, end_node): # 定义一个名为manhattan_dis的函数,接受两个参数cur_node(当前结点)和end_node(目标结点)
  2. # 获取当前结点和目标结点的状态矩阵
  3. cur_state = cur_node.state
  4. end_state = end_node.state
  5. dist = 0
  6. N = len(cur_state) # 获取状态矩阵的大小,假设为N
  7. # 遍历状态矩阵中的每个位置
  8. for i in range(N):
  9. for j in range(N):
  10. # 如果当前结点的值与目标结点的值相等,则跳过当前位置,因为这个位置已经在目标状态中
  11. if cur_state[i][j] == end_state[i][j]:
  12. continue
  13. num = cur_state[i][j] # 获取当前结点在状态矩阵中的值
  14. # 如果当前结点的值为0(空白格),则将目标位置设置为状态矩阵的右下角
  15. if num == 0:
  16. x = N - 1
  17. y = N - 1
  18. # 如果当前结点的值不为0,则根据当前结点的值计算其目标位置,假设目标位置为(x,y)
  19. else:
  20. x = num / N
  21. y = num - N * x - 1
  22. # 计算当前结点与目标位置之间的曼哈顿距离,并累加到总距离中
  23. dist += (abs(x - i) + abs(y - j))
  24. # 返回计算得到的曼哈顿距离作为当前结点到目标结点的估计代价
  25. return dist

3.预留占位函数

test_fn是一个占位函数,接受当前结点和目标结点作为参数。目前这个函数没有实际的功能。

  1. def test_fn(cur_node, end_node):
  2. return 0

4.生成子结点函数

创建generate_child函数,接受当前结点cur_node、目标结点end_node、哈希集合hash_set、OPEN表open_table和距离函数dis_fn作为参数。实现了在当前结点基础上生成可行的子结点,并考虑了重复状态的处理,是A*算法中搜索过程的重要一步。

  1. def generate_child(cur_node, end_node, hash_set, open_table, dis_fn):
  2. # 如果当前结点就是目标结点,则直接将目标结点假如OPEN表,并返回,表示已经找到了解
  3. if cur_node == end_node:
  4. heapq.heappush(open_table, end_node)
  5. return
  6. # 获取当前结点状态矩阵的大小
  7. num = len(cur_node.state)
  8. # 遍历当前结点状态矩阵的每一个位置
  9. for i in range(0, num):
  10. for j in range(0, num):
  11. # 如果当前位置不是空格,则跳过,因为空格是可以移动的位置
  12. if cur_node.state[i][j] != 0:
  13. continue
  14. # 遍历当前位置的四个邻居位置,即上下左右四个方向
  15. for d in direction:
  16. x = i + d[0]
  17. y = j + d[1]
  18. if x < 0 or x >= num or y < 0 or y >=num:
  19. continue
  20. # 记录生成的结点数量
  21. global SUM_NODE_NUM
  22. SUM_NODE_NUM += 1
  23. # 交换空格和邻居位置的数字,生成一个新的状态矩阵
  24. state = copy.deepcopy(cur_node.state)
  25. state[i][j], state[x][y] = state[x][y], state[i][j]
  26. # 计算新状态矩阵的哈希值,并检查是否已经在哈希集合中存在,如果存在则表示已经生成过相同的状态,跳过
  27. h = hash(str(state))
  28. if h in hash_set:
  29. continue
  30. # 将新状态的哈希值添加到哈希集合中,计算新状态结点的gn(从起始结点到当前结点的代价)和hn(当前结点到目标结点的估计代价)
  31. hash_set.add(h)
  32. gn = cur_node.gn + 1
  33. hn = dis_fn(cur_node, end_node)
  34. # 创建新的状态结点对象,并将其加入到当前结点的子结点列表中,并将其加入到OPEN表中。
  35. node = State(gn, hn, state, h, cur_node)
  36. cur_node.child.append(node)
  37. heapq.heappush(open_table, node)

5.定义输出路径函数

定义了一个名为print_path的函数,接受一个参数node,表示目标结点。通过回溯父结点的方式,从目标结点一直回溯到起始结点,并将沿途经过的状态矩阵打印出来,以展示搜索路径。

  1. def print_path(node):
  2. # 获取从起始结点到目标结点的路径长度,即目标结点的实际代价
  3. num = node.gn
  4. # 定义了一个内部函数show_block,用于打印状态矩阵
  5. def show_block(block):
  6. print("---------------")
  7. for b in block:
  8. print(b)
  9. # 创建一个栈,用于存储路径中经过的结点
  10. stack = []
  11. # 从目标结点开始,沿着父结点指针一直回溯到起始结点,并将沿途经过的状态矩阵入栈
  12. while node.par is not None:
  13. stack.append(node.state)
  14. node = node.par
  15. stack.append(node.state)
  16. # 从栈中依次取出状态矩阵,并打印出来
  17. while len(stack) != 0:
  18. t = stack.pop()
  19. show_block(t)
  20. # 返回路径长度
  21. return num

6.定义A*算法

定义A_start函数,接受起始状态start、目标状态end、距离函数distance_fn、生成子结点函数generate_child_fn和可选的时间限制time_limit作为参数。实现了A*算法的整个搜索过程,包括结点的扩展、路径的搜索和时间限制的处理。

  1. def A_start(start, end, distance_fn, generate_child_fn, time_limit=10):
  2. # 创建起始状态结点和目标状态结点对象,并分别计算其哈希值
  3. root = State(0, 0, start, hash(str(BLOCK)), None)
  4. end_state = State(0, 0, end, hash(str(GOAL)), None)
  5. # 检查起始状态是否就是目标状态,如果是,则直接输出提示信息
  6. if root == end_state:
  7. print("start == end !")
  8. # 将起始状态结点加入到OPEN表中,并对OPEN表进行堆化操作
  9. OPEN.append(root)
  10. heapq.heapify(OPEN)
  11. # 创建一个哈希集合,用于存储已经生成的状态结点的哈希值,并将起始状态结点的哈希值添加到集合中
  12. node_hash_set = set()
  13. node_hash_set.add(root.hash_value)
  14. # 记录算法开始的时间
  15. start_time = datetime.datetime.now()
  16. # 进入主循环,直到OPEN表为空(搜索完成)或达到时间限制
  17. while len(OPEN) != 0:
  18. top = heapq.heappop(OPEN)
  19. # 如果当前结点就是目标状态结点,则直接输出路径
  20. if top == end_state:
  21. return print_path(top)
  22. # 产生孩子节点,孩子节点加入OPEN表
  23. generate_child_fn(cur_node=top, end_node=end_state, hash_set=node_hash_set,
  24. open_table=OPEN, dis_fn=distance_fn)
  25. # 记录当前时间
  26. cur_time = datetime.datetime.now()
  27. # 超时处理,如果运行时间超过了设定的时间限制,则输出超时提示信息并返回
  28. if (cur_time - start_time).seconds > time_limit:
  29. print("Time running out, break !")
  30. print("Number of nodes:", SUM_NODE_NUM)
  31. return -1
  32. # 如果循环结束时OPEN表为空,则表示没有找到路径,输出提示信息并返回-1
  33. print("No road !") # 没有路径
  34. return -1

7.读取数据作为原始状态

定义read_block函数,接受三个参数block(状态矩阵列表)、line(输入的一行数据)、N(状态矩阵的大小)。将文本数据解析为状态矩阵的形式,并存储在列表中,为后续的状态表示和求解提供原始数据。

  1. def read_block(block, line, N):
  2. # 使用正则表达式提取输入行中的数字数据,并存储在列表res中
  3. pattern = re.compile(r'\d+') # 正则表达式提取数据
  4. res = re.findall(pattern, line)
  5. # 初始化计数变量t和临时列表tmp
  6. t = 0
  7. tmp = []
  8. # 遍历提取的数字数据,将其转换为整数,并添加到临时列表tmp中
  9. for i in res:
  10. t += 1
  11. tmp.append(int(i))
  12. # 当计数变量t达到状态矩阵的大小N时,表示当前行数据处理完毕,将临时表添加到状态矩阵列表中,并清空临时表
  13. if t == N:
  14. t = 0
  15. block.append(tmp)
  16. tmp = []

8.定义主函数查看结果

通过主函数if __name__ == 'main'读取输入数据、调用A*算法求解八数码问题,并输出求解结果的相关信息。

  1. if __name__ == '__main__':
  2. # 尝试打开infile.txt文件,如果文件打开失败,则输出错误信息并退出程序
  3. try:
  4. file = open('infile.txt', "r")
  5. except IOError:
  6. print("can not open file infile.txt !")
  7. exit(1)
  8. # 打开名为infile.txt文件,并将文件对象赋值给变量f
  9. f = open("infile.txt")
  10. # 读取文件的第一行,获取棋盘的大小NUMBER
  11. NUMBER = int(f.readline()[-2])
  12. # 根据棋盘大小生成目标状态,并将目标状态存储在列表GOAL中
  13. n = 1
  14. for i in range(NUMBER):
  15. l = []
  16. for j in range(NUMBER):
  17. l.append(n)
  18. n += 1
  19. GOAL.append(l)
  20. GOAL[NUMBER - 1][NUMBER - 1] = 0
  21. # 逐行读取文件中的数据
  22. for line in f: # 读取每一行数据
  23. # 在每次处理新的输入数据之前,需要清空OPEN表和BLOCK表
  24. OPEN = []
  25. BLOCK = []
  26. # 调用读取数据的函数,将当前行的数据解析并存储为状态矩阵
  27. read_block(BLOCK, line, NUMBER)
  28. # 初始化生成的结点数量为0
  29. SUM_NODE_NUM = 0
  30. # 记录算法开始的时间
  31. start_t = datetime.datetime.now()
  32. # 这里添加5秒超时处理,可以根据实际情况选择启发函数
  33. # 将求解路径长度存储在length中
  34. length = A_start(BLOCK, GOAL, manhattan_dis, generate_child, time_limit=10)
  35. # 记录算法结束时间
  36. end_t = datetime.datetime.now()
  37. # 如果找到了路径,则输出路径长度、算法执行时间和生成的结点数量
  38. if length != -1:
  39. print("length =", length)
  40. print("time =", (end_t - start_t).total_seconds(), "s")
  41. print("Nodes =", SUM_NODE_NUM)

四、运行结果

A*算法在解决八数码问题中表现出较高的准确性。通过启发式函数曼哈顿距离的计算,能够较准确的评估当前结点到目标节点的代价,并在搜索过程中选择代价最小的路径。通过和实际路径长度的比较,可以验证算法的准确性。

同时,A*算法在搜索过程中充分利用了启发式函数的估计值,能够更优先的扩展可能更接近目标的结点,从而提高搜索效率,但是,在某些复杂的情况下,仍可能耗费较长时间或无法找到解,这取决于问题的复杂度和启发式函数的选择。

以下结果显示的是从初始状态转变成目标状态的一个具体过程。

  1. ---------------
  2. [7, 2, 6]
  3. [8, 1, 4]
  4. [3, 5, 0]
  5. ---------------
  6. [7, 2, 6]
  7. [8, 1, 0]
  8. [3, 5, 4]
  9. ---------------
  10. [7, 2, 0]
  11. [8, 1, 6]
  12. [3, 5, 4]
  13. ---------------
  14. [7, 0, 2]
  15. [8, 1, 6]
  16. [3, 5, 4]
  17. ---------------
  18. [7, 1, 2]
  19. [8, 0, 6]
  20. [3, 5, 4]
  21. ---------------
  22. [7, 1, 2]
  23. [8, 5, 6]
  24. [3, 0, 4]
  25. ---------------
  26. [7, 1, 2]
  27. [8, 5, 6]
  28. [0, 3, 4]
  29. ---------------
  30. [7, 1, 2]
  31. [0, 5, 6]
  32. [8, 3, 4]
  33. ---------------
  34. [0, 1, 2]
  35. [7, 5, 6]
  36. [8, 3, 4]
  37. ---------------
  38. [1, 0, 2]
  39. [7, 5, 6]
  40. [8, 3, 4]
  41. ---------------
  42. [1, 5, 2]
  43. [7, 0, 6]
  44. [8, 3, 4]
  45. ---------------
  46. [1, 5, 2]
  47. [7, 3, 6]
  48. [8, 0, 4]
  49. ---------------
  50. [1, 5, 2]
  51. [7, 3, 6]
  52. [8, 4, 0]
  53. ---------------
  54. [1, 5, 2]
  55. [7, 3, 0]
  56. [8, 4, 6]
  57. ---------------
  58. [1, 5, 2]
  59. [7, 0, 3]
  60. [8, 4, 6]
  61. ---------------
  62. [1, 5, 2]
  63. [7, 4, 3]
  64. [8, 0, 6]
  65. ---------------
  66. [1, 5, 2]
  67. [7, 4, 3]
  68. [0, 8, 6]
  69. ---------------
  70. [1, 5, 2]
  71. [0, 4, 3]
  72. [7, 8, 6]
  73. ---------------
  74. [1, 5, 2]
  75. [4, 0, 3]
  76. [7, 8, 6]
  77. ---------------
  78. [1, 0, 2]
  79. [4, 5, 3]
  80. [7, 8, 6]
  81. ---------------
  82. [1, 2, 0]
  83. [4, 5, 3]
  84. [7, 8, 6]
  85. ---------------
  86. [1, 2, 3]
  87. [4, 5, 0]
  88. [7, 8, 6]
  89. ---------------
  90. [1, 2, 3]
  91. [4, 5, 6]
  92. [7, 8, 0]
  93. length = 22
  94. time = 0.09839 s
  95. Nodes = 8274
  96. 进程已结束,退出代码为 0

五、完整代码

  1. import heapq
  2. import copy
  3. import re
  4. import datetime
  5. BLOCK = []
  6. GOAL = []
  7. direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
  8. OPEN = []
  9. SUM_NODE_NUM = 0
  10. class State(object):
  11. def __init__(self, gn=0, hn=0, state=None, hash_value=None, par=None):
  12. self.gn = gn
  13. self.hn = hn
  14. self.fn = self.gn + self.hn
  15. self.child = []
  16. self.par = par
  17. self.state = state
  18. self.hash_value = hash_value
  19. def __lt__(self, other):
  20. return self.fn < other.fn
  21. def __eq__(self, other):
  22. return self.hash_value == other.hash_value
  23. def __ne__(self, other):
  24. return not self.__eq__(other)
  25. def manhattan_dis(cur_node, end_node):
  26. cur_state = cur_node.state
  27. end_state = end_node.state
  28. dist = 0
  29. N = len(cur_state)
  30. for i in range(N):
  31. for j in range(N):
  32. if cur_state[i][j] == end_state[i][j]:
  33. continue
  34. num = cur_state[i][j]
  35. if num == 0:
  36. x = N - 1
  37. y = N - 1
  38. else:
  39. x = num / N
  40. y = num - N * x - 1
  41. dist += (abs(x - i) + abs(y - j))
  42. return dist
  43. def test_fn(cur_node, end_node):
  44. return 0
  45. def generate_child(cur_node, end_node, hash_set, open_table, dis_fn):
  46. if cur_node == end_node:
  47. heapq.heappush(open_table, end_node)
  48. return
  49. num = len(cur_node.state)
  50. for i in range(0, num):
  51. for j in range(0, num):
  52. if cur_node.state[i][j] != 0:
  53. continue
  54. for d in direction:
  55. x = i + d[0]
  56. y = j + d[1]
  57. if x < 0 or x >= num or y < 0 or y >= num:
  58. continue
  59. global SUM_NODE_NUM
  60. SUM_NODE_NUM += 1
  61. state = copy.deepcopy(cur_node.state)
  62. state[i][j], state[x][y] = state[x][y], state[i][j]
  63. h = hash(str(state))
  64. if h in hash_set:
  65. continue
  66. hash_set.add(h)
  67. gn = cur_node.gn + 1
  68. hn = dis_fn(cur_node, end_node)
  69. node = State(gn, hn, state, h, cur_node)
  70. cur_node.child.append(node)
  71. heapq.heappush(open_table, node)
  72. def print_path(node):
  73. num = node.gn
  74. def show_block(block):
  75. print("---------------")
  76. for b in block:
  77. print(b)
  78. stack = []
  79. while node.par is not None:
  80. stack.append(node.state)
  81. node = node.par
  82. stack.append(node.state)
  83. while len(stack) != 0:
  84. t = stack.pop()
  85. show_block(t)
  86. return num
  87. def A_start(start, end, distance_fn, generate_child_fn, time_limit=10):
  88. root = State(0, 0, start, hash(str(BLOCK)), None)
  89. end_state = State(0, 0, end, hash(str(GOAL)), None)
  90. if root == end_state:
  91. print("start == end !")
  92. OPEN.append(root)
  93. heapq.heapify(OPEN)
  94. node_hash_set = set()
  95. node_hash_set.add(root.hash_value)
  96. start_time = datetime.datetime.now()
  97. while len(OPEN) != 0:
  98. top = heapq.heappop(OPEN)
  99. if top == end_state:
  100. return print_path(top)
  101. generate_child_fn(cur_node=top, end_node=end_state, hash_set=node_hash_set,
  102. open_table=OPEN, dis_fn=distance_fn)
  103. cur_time = datetime.datetime.now()
  104. if (cur_time - start_time).seconds > time_limit:
  105. print("Time running out, break !")
  106. print("Number of nodes:", SUM_NODE_NUM)
  107. return -1
  108. print("No road !")
  109. return -1
  110. def read_block(block, line, N):
  111. pattern = re.compile(r'\d+')
  112. res = re.findall(pattern, line)
  113. t = 0
  114. tmp = []
  115. for i in res:
  116. t += 1
  117. tmp.append(int(i))
  118. if t == N:
  119. t = 0
  120. block.append(tmp)
  121. tmp = []
  122. if __name__ == '__main__':
  123. try:
  124. file = open('infile.txt', "r")
  125. except IOError:
  126. print("can not open file infile.txt !")
  127. exit(1)
  128. f = open("infile.txt")
  129. NUMBER = int(f.readline()[-2])
  130. n = 1
  131. for i in range(NUMBER):
  132. l = []
  133. for j in range(NUMBER):
  134. l.append(n)
  135. n += 1
  136. GOAL.append(l)
  137. GOAL[NUMBER - 1][NUMBER - 1] = 0
  138. for line in f:
  139. OPEN = []
  140. BLOCK = []
  141. read_block(BLOCK, line, NUMBER)
  142. SUM_NODE_NUM = 0
  143. start_t = datetime.datetime.now()
  144. length = A_start(BLOCK, GOAL, manhattan_dis, generate_child, time_limit=10)
  145. end_t = datetime.datetime.now()
  146. if length != -1:
  147. print("length =", length)
  148. print("time =", (end_t - start_t).total_seconds(), "s")
  149. print("Nodes =", SUM_NODE_NUM)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/738907
推荐阅读
相关标签
  

闽ICP备14008679号