call(back)
Algorithms & Data StructuresmediumSign in to star problems

Exact Board Jumps II

You are given board, an array of non-negative integers, and a start index. From index i you may move exactly board[i] steps left or right, staying in bounds. Return the minimum number of moves to reach the last index, or -1 if it can't be reached.

board = [1, 2, 2, 2, 6, 1], start = 0  => 3    (0 -> 1 -> 3 -> 5)
board = [2, 0, 1, 3],       start = 1  => -1   (board[1] = 0 traps you)
board = [5, 2, 7],          start = 2  => 0

Hints

Hint 1

Each index has at most two out-edges: i - board[i] and i + board[i]. Every move costs one, so this is an unweighted shortest path.

Hint 2

BFS assigns every reachable index its minimum move count. Mark an index visited when you enqueue it — a zero cell is its own neighbor.

Asked at