Why it works
- A square is a state and a roll is an edge, so every move costs the same: BFS takes squares in order of moves, and the first time it reaches the last square is the fewest moves.
- The ladder or snake is followed before the square is stored, because you end the move where it takes you: landing on 2 means standing on 11.
- A square already in dist was reached in as few moves or fewer, so it is skipped and nothing is queued twice.
Complexity
Time O(n²): each of the n² squares is queued at most once and tries at most 6 rolls. Memory O(n²) for dist and the queue.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗