在Golang中构建跳跃游戏的程序

85 阅读1分钟

概述

提供了一个输入数组。数组中的每个条目代表从该位置开始的最大跳跃长度。一个人应该从第一个索引开始,如果可以到达最后一个索引,则返回true;如果不能到达最后一个索引,则返回false。

例子

Input: [2, 3, 1, 1, 4]
Output: true

Input: [3, 2, 1, 0, 4]
Output: false

在第一个例子中,有不同的方法来到达最后一个索引。

  • 0-1-4

  • 0-2-3-4

在第二个例子中,没有办法达到最后的索引。你能达到的最好结果是倒数第二个指数。由于第二个索引的值是零,因此不可能达到最后一个索引。

程序

package main

import "fmt"

func canJump(nums []int) bool {
	lenNums := len(nums)
	canJumpB := make([]bool, lenNums)

	canJumpB[0] = true

	for i := 0; i < lenNums; i++ {

		if canJumpB[i] {
			valAtCurrIndex := nums[i]
			for k := 1; k <= valAtCurrIndex && i+k < lenNums; k++ {
				canJumpB[i+k] = true
			}
		}

	}

	return canJumpB[lenNums-1]
}

func main() {
	input := []int{2, 3, 1, 1, 4}

	canJumpOrNot := canJump(input)
	fmt.Println(canJumpOrNot)

	input = []int{3, 2, 1, 0, 4}

	canJumpOrNot = canJump(input)
	fmt.Println(canJumpOrNot)

}

输出

true
false