Fastest algorithm to hop through an array

后端 未结 10 1362
栀梦
栀梦 2021-02-05 16:52

Start with an array A of positive numbers. Start at index 0. From index i, you can move to index i+x for any x <= A[i]. The goal is to find the minimum number of moves needed

10条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 17:21

    You can convert the array into a graph and find the shortest path. Here is how the transformation from array to graph should work.

    Each array element is an node. And, based on the value in the array element a edge to drawn between the node to the other indices(nodes) we can jump to. Once we have this graph we can find shortest path, which is better than O(n^2).

    http://i.imgur.com/Ih3UP.png

提交回复
热议问题