Fastest algorithm to hop through an array

后端 未结 10 1110
栀梦
栀梦 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:19

    You could formulate it as a graph algorithm (really, what problem can't be?). Let the positions in the array be the vertices, and the possible destinations have an edge from each vertex. In your example, vertex 0 would have edges to 1 and 2, while vertex 1 would have edges to 2, 3, 4 and 5.

    There are several efficient graph search algorithms. For instance, Dijkstra's is O(|E| + |V|log|V|), and A* is O(log h*), which is better if you can come up with a good heuristic.

提交回复
热议问题