【问题标题】:minimum of jumps required to reach end of array - get index positions到达数组末尾所需的最少跳转 - 获取索引位置
【发布时间】:2014-02-21 00:01:41
【问题描述】:

问题是获取minimum jumps 和数组中的相应索引,这些索引会导致array 的结尾以较少的跳转。例如: {3,2,3,1,5,4} 将占用 2 jumps。

Jump 1 from index 0 to index 2 
jump 2 from index 2 to index 5 

跳跃,我的意思是跳跃;即需要多少跳。如果您是特定索引,则可以按该索引中的值进行跳转。

这是我在Java 中的实现,它正确地给出了最少的跳跃次数,但是我很难更新listindices 对应的跳跃位置。我怎样才能让它工作?

public static int minJumps2(int[] arr, List<Integer> jumps){
        int minsteps=0;
        boolean reachedEnd=false;
        if (arr.length<2)
            return 0;
        int farthest=0;
        for (int i=0;i<=farthest;i++){
             farthest=Math.max(farthest, arr[i]+i);
             if (farthest>=arr.length-1){
                 jumps.add(i);
                 reachedEnd=true;
                 break;
             }
             //jumps.add(farthest);
             minsteps++;

        }
        if (!reachedEnd){
            System.out.println("unreachable");
            return -1;
        }
        System.out.println(minsteps);
        System.out.println(jumps);
        return minsteps;
    }

public static void main(String[] args){

        int[] arr= {3,2,3,1,5};
        List<Integer> jumps=new ArrayList<Integer>();
        minJumps2(arr,jumps);

    }

我正在使用此处描述的跳跃游戏算法:Interview puzzle: Jump Game

【问题讨论】:

  • 请清除您的问题。什么是跳跃?为什么不能一次从索引 0 跳到末尾。
  • 我已经编辑了这个问题,如果有帮助的话

标签: java arrays algorithm


【解决方案1】:

我看到你已经接受了一个答案,但我有代码可以满足你的需要:

-它打印出最小跳跃的路径(不仅仅是一个,而是全部)。

-它还会告诉你数组的末尾是否不可到达。

使用DP,复杂度=O(nk),其中n为数组长度,k为最大元素的数值在数组中。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MinHops {

    private static class Node {
        int minHops;
        int value;
        List<Node> predecessors = new ArrayList<>();

        Node(int distanceFromStart, int value) {
            this.minHops = distanceFromStart;
            this.value = value;
        }
    }

    public static void allMinHopsToEnd(int[] arr) {
        Node[] store = new Node[arr.length];
        store[0] = new Node(0, arr[0]);
        for (int i = 1; i < arr.length; i++) {
            store[i] = new Node(Integer.MAX_VALUE, arr[i]);
        }

        for (int index = 0; index < arr.length; index++) {
            try {
                updateHopsInRange(arr, store, index);
            } catch (RuntimeException r) {
                System.out.println("End of array is unreachable");
                return;
            }
        }

        Node end = store[store.length-1];
        List<ArrayList<Integer>> paths = pathsTo(end);
        System.out.println("min jumps for: " + Arrays.toString(arr));
        for (ArrayList<Integer> path : paths) {
            System.out.println(path.toString());
        }

        System.out.println();
    }

    private static void updateHopsInRange(int[] arr, Node[] store, int currentIndex) {
        if (store[currentIndex].minHops == Integer.MAX_VALUE) {
            throw new RuntimeException("unreachable node");
        }

        int range = arr[currentIndex];
        for (int i = currentIndex + 1; i <= (currentIndex + range); i++) {
            if (i == arr.length) return;
            int currentHops = store[i].minHops; 
            int hopsViaNewNode = store[currentIndex].minHops + 1;

            if (hopsViaNewNode < currentHops) { //strictly better path
                store[i].minHops = hopsViaNewNode;
                store[i].predecessors.clear();
                store[i].predecessors.add(store[currentIndex]);
            } else if (hopsViaNewNode == currentHops) { //equivalently good path
                store[i].predecessors.add(store[currentIndex]);
            }
        }
    }

    private static List<ArrayList<Integer>> pathsTo(Node node) {
        List<ArrayList<Integer>> paths = new ArrayList<>();
        if (node.predecessors.size() == 0) {
            paths.add(new ArrayList<>(Arrays.asList(node.value)));
        }

        for (Node pred : node.predecessors) {
            List<ArrayList<Integer>> pathsToPred = pathsTo(pred);
            for (ArrayList<Integer> path : pathsToPred) {
                path.add(node.value);
            }

            paths.addAll(pathsToPred);
        }

        return paths;
    }

    public static void main(String[] args) {
        int[] arr = {4, 0, 0, 3, 6, 5, 4, 7, 1, 0, 1, 2};
        int[] arr1 = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        int[] arr2 = {2, 3, 1, 1, 4};
        int[] arr3 = {1, 0, 0, 4, 0};
        allMinHopsToEnd(arr);
        allMinHopsToEnd(arr1);
        allMinHopsToEnd(arr2);
        allMinHopsToEnd(arr3);
    }

}

【讨论】:

    【解决方案2】:

    虽然我没有清楚地理解您的问题,但似乎您需要在增加minsteps++ 时将索引添加到jumps

    您需要取消注释jumps.add(farthest); 并传递i 而不是farthest。此外,您可能需要在 if 条件下删除 jumps.add(i)。希望这会有所帮助。

    编辑: 看起来你的逻辑很好,除了第一次跳转总是在索引0 处。所以在你的循环之前添加0到你的jumps

    更新 好的,我没有经过测试,也没有通过您提供的算法链接。该算法解释说,我们需要考虑一个元素e 和索引i,并将元素的max 从当前位置获取到arr[e],但这并没有发生。我试图复制提到的解决方案的确切步骤。希望这对您有所帮助。

    public static int minJumps2(int[] arr, List<Integer> jumps) {
            boolean reachedEnd = false;
            if (arr.length < 2)
                return 0;
    
            //calculate (index + value)
            int[] sums = new int[arr.length];
            for (int i = 0; i < arr.length; i++) {
                sums[i] = i + arr[i];
            }
            // start with first index
            jumps.add(0);
    
            while (true) {
                int currentPosition = jumps.get(jumps.size() - 1);
                int jumpValue = arr[currentPosition];
    
                // See if we can jump to the goal
                if (arr.length - 1 - currentPosition <= jumpValue) {
                    jumps.add(arr.length - 1);
                    reachedEnd = true;
                    break;
                } else {
                    int maxIndex = currentPosition;
                    int currentMax = sums[maxIndex];
                    // max of the reachable elements
                    for (int i = currentPosition; i <= currentPosition + jumpValue; i++) {
                        if (sums[i] > currentMax) {
                            maxIndex = i;
                            currentMax = sums[i];
                        }
                    }
                    if (maxIndex == currentPosition) { 
                        break; 
                    }
    
                    jumps.add(maxIndex);
                }
            }
            System.out.println(jumps.size());
            System.out.println(jumps);
            return jumps.size();
        }
    

    【讨论】:

    • 我不是反对者,但这一个不起作用。你测试了吗?而system.out.println(jumps)将打印实际内容,因为它是一个列表而不是数组。
    • 好吧,我有点被忽视和过度退出。请尝试更新的答案。
    • 你能解释一下 sums 数组的用途吗?
    猜你喜欢
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2020-07-29
    • 2015-03-07
    • 1970-01-01
    • 2020-11-25
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多