AlgoViz

Minimum multiplications to reach end

Hard

BFS over the 100000 residues

Problem

From start, repeatedly multiply by array values mod 100000 to reach end; return the fewest steps.

In simple words

BFS over numbers mod 100000, where each multiplier is an edge; the fewest multiplications is shortest.

The idea

Each reachable value modulo 100000 is a vertex, and multiplying by an array element is an edge of cost one. BFS therefore gives the fewest multiplications, over a state space small enough to enumerate.

The trick

  • The state space is bounded at 100000 by the modulus.
  • All edges cost one, so BFS suffices.
  • Return -1 when the target is unreachable.
R
F
F
F
F
·
·
F
F
minute0
fresh6

Step 1 of 6. Every rotten orange (R) rots its fresh (F) neighbours each minute — a multi-source BFS. minute 0, fresh 6.

1/6
Optimal
timeO(rows·cols)spaceO(rows·cols)

All sources start at minute 0.

1// enqueue all rotten cells; BFS by layers,2// converting fresh neighbors, counting minutes.3while (q.length && fresh > 0) {4  minutes++;5  for (let n = q.length; n > 0; n--) spread(q.shift());6}7return fresh === 0 ? minutes : -1;

Input

grid
3 × 3

Memory

minute
0
fresh
6

Output

minute
0
fresh
6
answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
start=3, end=30, arr=[2,5,7]
Output:
2
Explanation:
3×2=6, 6×5=30 → 2 steps.

Example 2

Input:
start=7, end=66175, arr=[3,4,65]
Output:
4
Explanation:
Reached in 4 multiplications.

Example 3

Input:
start=5, end=5, arr=[2,3]
Output:
0
Explanation:
Already there → 0.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.