[LeetCode]Jump Game II、Jump Game

本文探讨了如何通过BFS算法解决跳步游戏问题,旨在找到从起始位置到达目标位置所需的最少跳跃次数。通过实例演示,展示了如何利用连续节点特性优化BFS过程,同时处理无法到达目标的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Jump Game II:

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

按题意就是跳到最后一格最少需要几跳,其实把跳达想像成连接关系的话,很明显是做个BFS求最短距离而已。

传统的BFS要个栈,但是如果你脑补一下BFS一层层扩展的过程的话,就发现每一层的所有节点其实在数组上都是连续的,用两个Index来标志这两层就好了嘛。

这样的好处就是不用额外的空间了。

下面[pre,farest]就是当前可以跳达的一层,然后whilie里的循环就是根据这一层得到下一层的新的farest区间。

题目没有说跳达不了的情况,这里一并处理了,跳不到会返回-1.

class Solution {
public:
    int jump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        assert(A&&n>=0);
	    if ( n<=1 )
		    return 0;
	    int pre=0,farest=A[0];
	    int curJump=1;
	    while(pre<farest)
	    {
		    if ( farest>=n-1 )
			    return curJump;
		    int t=farest;
		    while(pre<=t)
		    {
			    farest=max(farest,A[pre]+pre);
			    ++pre;
		    }
		    --pre;
		    curJump++;
	    }
	    return -1;
    }
};


Jump Game:

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

跟上一题是一个问题,改一下返回值就可以了。

class Solution {
public:
    bool canJump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        assert(A&&n>=1);
	    int pre=0,far=A[0];
	    while(pre<=far)
	    {
		    if ( far>=n-1)
			    return true;
		    int tmp=far;
		    while(pre<=tmp)
		    {
			    far=max(far,A[pre]+pre);
			    pre++;
		    }
	    }
	    return false;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值