python代码实现八数码深度优先搜索策略
import numpy as np
import copy
from datetime import datetime
#定位元素0的位置
def local(S0):
a = np.array(S0)
i,j = np.where(a == 0)
return i[0],j[0]
#操作算子
def right_(S0):
i,j = local(S0)
arr = copy.deepcopy(S0)
if j in (0,len(S0)-2):
arr[i][j], arr[i][j+1] = arr[i][j+1],arr[i][j]
return arr
def left_(S0):
i,j = local(S0)
arr = copy.deepcopy(S0)
if j in (1,len(S0)-1):
arr[i][j],arr[i][j-1] = arr[i][j-1],arr[i][j]
return arr
def up_(S0):
i,j = local(S0)
arr = copy.deepcopy(S0)
if i in (1,len(S0)-1):
arr[i][j],arr[i-1][j] = arr[i-1][j],arr[i][j]
return arr
def down_(S0):
i,j = local(S0)
arr = copy.deepcopy(S0)
if i in (0,len(S0)-2):
arr[i][j],arr[i+1][j] = arr[i+1][j],arr[i][j]
return arr
#定义一个节点类
class Node:
def __init__(self,data,level,parent):
self.data=data
self.level=level
self.parent = parent
if __name__ == "__main__":
# S0 = [[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]
# Sg = [[4,1,2,3],[0,5,6,7],[8,9,10,11],[12,13,14,15]]
# S0 = [[0,1],[2,3]]
# Sg = [[3,1],[2,0]]qq
S0=[[0,1,3],[4,2,5],[7,8,6]]
Sg=[[4,1,3],[7,0,5],[8,2,6]]
# a=[0,1,3,4,2,5,7,8,6]
# b=[4,1,3,7,0,5,8,2,6]
Node0 = Node(S0,0,"None")
# print(Node0.data)
deep_level = 6
open_ = [Node0]
close = []
# level = 1
step = 0
start = datetime.now()
while len(open_) > 0:
step = step + 1
n = open_.pop(0)
# print("1111",Node0.data)
close.append(n)
# 如果找到目标结果,则输出其最优路径。
if n.data == Sg:
print( n.data,'true','搜索完毕!')
result = []
result.append(n)
while n.parent!="None":
result.append(n.parent)
n = n.parent
for j in range(len(result)):
print(str(j)+"->")
result_0 = result.pop(-1)
print(result_0.data)
print("------------结束搜索-----------")
break
else:
if n.level<=int(deep_level):
local(n.data)
Up = up_(n.data)
if Up not in [open_[i].data for i in range(len(open_))] and Up not in [close[i].data for i in range(len(close))] and Up is not None:
Node0 = Node(Up,n.level+1,n)
open_.insert(0,Node0)
Down = down_(n.data)
if Down not in [open_[i].data for i in range(len(open_))] and Down not in [close[i].data for i in range(len(close))] and Down is not None:
Node0 = Node(Down,n.level+1,n)
open_.insert(0,Node0)
Left = left_(n.data)
if Left not in [open_[i].data for i in range(len(open_))] and Left not in [close[i].data for i in range(len(close))] and Left is not None:
Node0 = Node(Left,n.level+1,n)
open_.insert(0,Node0)
Right = right_(n.data)
if Right not in [open_[i].data for i in range(len(open_))] and Right not in [close[i].data for i in range(len(close))] and Right is not None:
Node0 = Node(Right,n.level+1,n)
open_.insert(0,Node0)
# Asort(open_)
print("第"+ str(step)+"次查找,中间项为:",Node0.data,"深度为:",Node0.level)
end = datetime.now()
print('共耗时:', end - start)
搜索结果:

这段Python代码展示了如何使用深度优先搜索(DFS)解决经典的八数码问题。它定义了四个基本操作(上、下、左、右),创建了一个节点类来存储状态和层级信息,并通过一个开放列表和关闭列表进行搜索。当找到目标状态时,会打印出最优路径。程序还计算了搜索过程中的步数和总耗时。
3828





