最小步骤数
题目描述
一个正整数数组,设为nums
最大为100
个成员
求从第一个成员开始正好走到数组最后一个成员所使用的最小步骤数
要求:
- 第一步,必须从第一元素起,且
1 <= 第一步步长 < len / 2
(len为数组长度) - 从第二步开始只能以所在成员的数字走相应的步数,不能多不能少,如果目标不可达返回
-1
,只输出最小的步骤数量 - 只能向数组的尾部走不能向回走
输入描述
一个正整数数组,元素用空格
分割数组长度 < 100
输出描述
正整数,最小步数
不存在输出-1
示例一
输入
7 5 9 4 2 6 8 3 5 4 3 9
输出
2
说明
第一个可选步长选择2
从第一个成员7
开始走两步到9
第二步从9
经过9
个成员到最后
¶示例二
输入
1 2 3 7 1 5 9 3 2 1
输出-1
def read_data():
return [int(index) for index in input().split()]
nums = read_data()
for i in range(1, len(nums) // 2):
sum = i
count = 1
res = 100
length = len(nums)
while sum < length - 1:
sum = sum + nums[sum]
count = count + 1
if sum == length - 1:
res = min(count, res)
print(res if res != 100 else -1)