问题:给定一个非负整数数组,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个位置。
示例1:
输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
示例2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
分析:
此问题可用BFS来实现:
'''
图的广度优先搜索算法实现
建立数组上每个节点的邻居关系:
位置0的邻居为位置1和位置2,定义为字典:position['0']=['1','2']
位置1的邻居为位置2、3、4,定义为字典:position['1']=['2','3','4']
以此类推,位置20为终点
'''
from collections import deque #使用队列
#文件读取数据
#num_list=[2,3,1,1,4,2,5,2,1,4,1,3,8,4,0,1,1,1,5,0,1]
with open('numbers.txt','r') as fp:
number_string=fp.readline()
fp.close()
num_list=eval(number_string)
#数据整理
position={}#所有的邻居关系
for i in range(len(num_list)):
all_neighor=[] #all_neighor存取当前位置所有邻居
for j in range(1,num_list[i]+1):
if (i+j)<=20: #20为终点,计算出20以上的数没有意义
all_neighor.append(str(i+j))
position[str(i)]=all_neighor
for key,value in position.items():
print(key,'->',value)
#BFS实现
def search(positon:dict,start:str,end:str): #邻居关系 起点 终点
search_queue=deque() #创建一个队列
search_queue.extend(position[start])
searched=[] #用于记录已经进入过队列的数,防止某些位置重复进入队列造成死循环
while search_queue: #只要队列不为空
posi=search_queue.popleft()
#print(posi,end=' ')
if posi not in searched: #如果没检查过
if posi == end:
return True
#print('能走到数列的最后位置。')
else:
searched.append(posi)
if posi in position.keys(): #如果在字典内
# 将邻居都加入到队列中,+没有重载,用queue的内置函数extend
search_queue.extend(position[posi])#不是终点20就把所有可能位置加入队列
return False #如果不能到终点则返回false
with open('results.txt','w') as fp:
if search(position,'0','20'): #0为起点 20为终点
fp.write('能走到最后位置!')
else:
fp.write('不能走到最后位置!')
fp.close()