Problem 522503 · medium · Phase 05 Advanced Algorithms & Graphs

Bouncing to a Sunken Stone

graphs · BFS · implicit graph

A row of stepping stones is described by a list stones of non-negative integers. A frog sits on index start. Standing on index i, it may hop exactly stones[i] places to the left or exactly stones[i] places to the right, as long as it stays inside the row. A stone whose value is 0 is sunken.

Return the fewest hops the frog needs to stand on any sunken stone (0 if it already does), or -1 if it can never reach one.

Examples

Input:  stones = [3, 1, 2, 0, 2, 4], start = 5
Output: 3
Explanation: 5 -> 1 (hop 4 left) -> 0 (hop 1 left) -> 3 (hop 3 right).

    index:  0  1  2  3  4  5
    stones: 3  1  2  0  2  4

Input:  stones = [2, 5, 2], start = 0
Output: -1
Explanation: the frog can only bounce between indices 0 and 2.

Input:  stones = [0], start = 0
Output: 0

Constraints

  • 1 <= len(stones) <= 5 * 10**4, 0 <= stones[i] < len(stones), 0 <= start < len(stones)
  • Target O(n) time.

Goals

  • Recognise an array with jump rules as an implicit graph
  • Use BFS to count the fewest hops to any node with a property
Starting Python…