#每一个节点可以走的位置
zhaofa={
0:[4,6],
1:[6,8],
2:[7,9],
3:[4,8],
4:[3,9,0],
5:[],
6:[1,7,0],
7:[2,6],
8:[1,3],
9:[2,4]
}
level=0
times=0
N=4
#当前的位置
ongoing_nodes=[1]
#判断是否结束 1 到达了N步 2 前边没有可以走的
while(level<=N or len(ongoing_nodes)==0):
print (str(level))
print(ongoing_nodes)
#判断当前要走的节点集合中有没有包含目标节点 如果有就去除并且计数器加一
while True:
if 9 in ongoing_nodes:
times+=1
ongoing_nodes.remove(9)
else:
break
#广度优先搜索 开始下一步走
next_step_nodes=[]
for pos in ongoing_nodes:
next_step_nodes.extend(zhaofa[pos])
# 走到下一步
ongoing_nodes=next_step_nodes
#层数加一
level+=1
print(times)
输出结果是
0
[1]
1
[6, 8]
2
[1, 7, 0, 1, 3]
3
[6, 8, 2, 6, 4, 6, 6, 8, 4, 8]
4
[1, 7, 0, 1, 3, 7, 9, 1, 7, 0, 3, 9, 0, 1, 7, 0, 1, 7, 0, 1, 3, 3, 9, 0, 1, 3]
3