CodingNodes / Graphs / Snakes and Ladders System design Space play · ←→ step · R restart

Problem

A square board has n rows and n columns, with squares numbered 1 to n² in a zigzag: square 1 is the bottom-left cell, the bottom row runs left to right, the row above runs right to left, and so on.

board[r][c] is either -1 or the number of a square. If it is a number, then landing on that cell sends you to that square (a ladder if it is higher, a snake if it is lower). You follow at most one such jump per move, and the square you land on after a jump is not jumped from again.

You start on square 1. Each move you pick a number from 1 to 6 and advance that many squares (you may not go past square n²). Return the fewest moves needed to land on square n², or -1 if it is impossible.

Constraints

  • 2 ≤ n ≤ 20
  • board[r][c] is -1 or in the range [1, n²]
  • squares 1 and n² have no snake or ladder

Examples: pick one to animate

Solutions

TimeO(n²) SpaceO(n²)

Time: Each of the n² squares enters the queue at most once, and each one tries at most 6 rolls.

Space: The dist array and the queue hold up to n² + 1 numbers.

Treat each square as a node and each roll as an edge to the square you end on (after any snake or ladder). Every move costs one roll, so the fewest rolls is a shortest path in an unweighted graph. Breadth-first search with a queue reaches squares in order of rolls used, so the first time we reach the last square is the answer. A small helper turns a square number into a board row and column, flipping direction on every other row.