看到一个题目:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
百度参考了网友提供的BFS方法( 出处找不到了~~),顺利通过LeetCode测试,发布出来,记录下~
class Solution:
def __init__(self):
print("Begin to run solution....")
def jump2(self, nums) -> int:
if len(nums) == 1:
return 0
if nums[0] >= len(nums) - 1:
return 1
solutions = []
for i in range(1, nums[0] + 1):
solutions.append(self.minsteps_remain(1, nums[i:]))
return min(solutions)
def jump(self, nums) -> int:
# 最大跳力,BFS算法 转换为BFS问题(注:如果认真思考一下的话, 可以看成单源最短路径问题)。及第i层所有的节点都能够在i−1步下到达。例如 2 3 1 1 4 ==> 2 || 3 1 || 1 4 ||
if len(nums) < 2:
return 0
if nums[0] == 0:
return -1
currentMax = 0 # 当前层能到达的最大位置
nextMax = 0 # 下一层能到达的最大位置
level = 0 # 跳数,即层数
i = 0
while currentMax - i + 1 > 0:
level += 1
while i <= currentMax:
nextMax = max(nextMax, nums[i] + i)
i += 1
if nextMax >= len(nums) -1:
return level
currentMax = nextMax
return 0
def minsteps_remain(self, current_steps, nums_left):
remain_step = 0
if len(nums_left) == 0:
return 0
if len(nums_left) == 1:
return current_steps + 1
maxsteps = nums_left[0]
print("maxsteps = {}".format(maxsteps))
if maxsteps == 0:
return 1000000000000
if maxsteps >= (len(nums_left) -1):
return current_steps + 1
else:
# 针对每种情况都返回一个最短路径,最终就是最短
steps = []
for i in range(1, maxsteps + 1):
steps.append(self.minsteps_remain(current_steps, nums_left[i:]))
remain_step = min(steps)
return current_steps + remain_step
def add_cases(cases, results, case_result):
cases.append(case_result[0])
results.append(case_result[1])
if __name__ == "__main__":
solution1 = Solution()
cases = list()
results = list()
add_cases(cases, results, [[2,3,1,1,4], 2])
add_cases(cases, results, [[2,3,1,1,4], 2])
add_cases(cases, results, [[2,4,1,1,4], 2])
add_cases(cases, results, [[2,3,0,1,4], 2])
add_cases(cases, results, [[2,1,1,1,4], 3])
add_cases(cases, results, [[3,2,1,1,4], 2])
add_cases(cases, results, [[0], 0])
add_cases(cases, results, [[9], 0])
add_cases(cases, results, [[4,3,0,1,4], 1])
add_cases(cases, results, [[5,6,4,4,6,9,4,4,7,4,4,8,2,6,8,1,5,9,6,5,2,7,9,7,9,6,9,4,1,6,8,8,4,4,2,0,3,8,5], 10])
for i in range(len(cases)):
print("\n" * 2)
print("TEST CASE{} ---- {} \n".format(i, cases[i]))
case_result = solution1.jump(cases[i])
print("(target, result). ({}, {})".format(results[i], case_result))
if case_result != results[i]:
print("FAIL")
else:
print("SUCCESS")