字节跳动笔试1——马里奥弹跳板游戏(BFS)

题目

一个数组代表跳板,数字代表向前或向后可以跳的最大距离(比如3,那么跳1,、2、3都行),0代表悬崖(跳上去摔死)。
指定一个出生点P,求到终点需要跳的最小次数(终点是最后一个元素后面),无法到达输出-1

输入:
第一行:数组长度N,出生点P
第二行:N个数字
输出:
最小次数

示例:

输入:
7 4
10 0 2 1 1 0 1

输出:
3

1<= N <= 10000
1 <= P <= N

思路

LeetCode的jump game II, 但他只能往后跳。

最小次数,那么就是BFS了,动手写代码

代码

用一个队列实现BFS。

package shen.leetcode.solution.toutiao;

import java.util.LinkedList;

public class Solution_toutiao_0630 {

    public static void main(String[] args) {
        System.out.println(core(new int[]{10, 0, 2, 1, 1, 0, 1}, 7));
    }

    public static LinkedList<Node> q = new LinkedList<>();

    public static int core(int arr[], int start) {
        q.offer(new Node(start - 1, 0));
        while (!q.isEmpty()) {
            Node curNode = q.poll();
            if (arr[curNode.index] == 0) {
                continue;
            }
            int maxLength = arr[curNode.index];
            if (curNode.index + maxLength > arr.length - 1) {// 大于长度,说明可以到达终点,返回
                return curNode.step + 1;
            }
            if (curNode.index - maxLength >= 0) { // 可以往回跳
                for (int i = curNode.index - maxLength; i <= curNode.index - maxLength + 2 * arr[curNode.index]; i++) {
                    if (i == curNode.index) continue;
                    q.offer(new Node(i, curNode.step + 1));
                }
            } else {
                int begin = maxLength - curNode.index;
                for (int i = begin; i <= begin + 2 * arr[curNode.index] - begin; i++) {
                    if (i == curNode.index) continue;
                    q.offer(new Node(i, curNode.step + 1));
                }
            }

        }
        return -1;
    }

    public static class Node {
        int index;
        int step;

        public Node(int index, int step) {
            this.index = index;
            this.step = step;
        }
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值