到达阵列末端所需的最小跳跃 - 获得索引位置

时间:2014-02-21 00:01:42

标签: java arrays algorithm

问题是得到minimum jumps和数组中相应的索引,导致array的结尾跳跃较少。对于前: {3,2,3,1,5,4}需要2 jump

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

跳跃,我的意思是跳跃;即需要多少跳。如果你是一个特定的索引,你可以跳过该索引中的值。

以下是我在Java中的实现,它正确地给出了最小跳转次数,但是我很难更新list与跳转位置对应的indices。我怎样才能让它运作起来?

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);

    }

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

2 个答案:

答案 0 :(得分:2)

我看到你已经接受了答案,但我的代码可以满足您的需求:

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

- 它还会告诉您数组的末尾是否无法访问。

它使用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);
    }

}

答案 1 :(得分:1)

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

您需要取消评论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();
    }