资源简介
算法课程实验、大作业
代码片段和文件信息
# 计算状态对应的逆序数
def THEnum(node):
Sum = 0
for i in range(1 9):
num = 0
for j in range(0 i):
if node[j] > node[i] and node[i] != ‘0‘:
num = num + 1
Sum += num
return Sum
# h(n)函数,用于计算估价函数f(n),这里的h(n)选择的是与目标相比错位的数目
def Hn(node):
global goal
hn = 0
for i in range(0 9):
if node[i] != goal[i]:
hn += 1
return hn
# 拓展node状态对应的子结点
def Expand(node):
global expand
tnode = []
state = node.index(“0“)
elist = expand[state]
j = state
for i in elist:
j = state
if i > j:
i j = j i
re = node[:i] + node[j] + node[i + 1:j] + node[i] + node[j + 1:]
tnode.append(re)
return tnode
# 将最后的结果按格式输出
def PRINT(result):
for i in range(len(result)):
print(“step--“ + str(i + 1)+“|“)
print(“|“+result[i][:3]+“|“)
print(“|“+result[i][3:6]+“|“)
print(“|“+result[i][6:]+“|“)
# 选择opened表中的最小的估价函数值对应的状态
def MIN(opened):
ll = {}
for node in opened:
k = Fn[node]
ll[node] = k
kk = min(ll key=ll.get)
return kk
# 主程序开始
opened = []
closed = []
Gn = {} # 用来存储状态和对应的深度,也就是初始结点到当前结点的路径长度
Fn = {} # 用来存放状态对应的估价函数值
parent = {} # 用来存储状态对应的父结点
# expand中存储的是九宫格中每个位置对应的可以移动的情况
# 当定位了0的位置就可以得知可以移动的情况
expand = {0: [1 3] 1: [0 2 4] 2: [1 5]
3: [0 4 6] 4: [3 1 5 7] 5: [4 2 8]
6: [3 7] 7: [6 4 8] 8: [7 5]}
print(“若输入‘123405678’代表8数码的状态为:“)
print(“|123|“)
print(“|405|“)
print(“|678|“)
start = input(“请输入初始状态:
评论
共有 条评论