题解 | #袋鼠过河#

袋鼠过河

https://www.nowcoder.com/practice/74acf832651e45bd9e059c59bc6e1cbf

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {


    static List<Integer> resu = new ArrayList<>();
    static int[][] used;

    // 贪心算法 每次跳动最大值
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] step = new int[n];
        for (int i = 0; i < n; i++) {
            step[i] = in.nextInt();
        }
        used = new int[n][n];
        startDri(step, 0, 0);
        if (resu.size() > 0) {
            Collections.sort(resu);
            System.out.println(resu.get(0));
        }else
        System.out.println(-1);

    }

    private static void startDri(int[] step, int index, int count) {

        if (used[index][count] == 1) {
            return;
        }
        used[index][count] = 1;
        if (index + step[index] > step.length - 1) {
            resu.add(count + 1);
            return;
        }
        if (step[index] == 0) {
            return;
        }
        int maxLength = index + step[index];

        for (int i = index + 1; i < step.length && i <= maxLength; i++) {
            startDri(step, i, count + 1);
        }

    }
}

全部评论

相关推荐

学历算污点吗?
小何和:快毕业了,BOSS上的od闻着味就来了
点赞 评论 收藏
分享
迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务