Snakes and Ladders

Medium

Topics
ArrayBFSMatrix

grid is an n by n board whose squares are numbered 1 to n * n in boustrophedon order: starting at the bottom-left, left to right along the bottom row, then right to left along the row above it, alternating all the way up.

From square x you may move to any of x + 1 through x + 6 that is on the board. If the square you land on holds a value other than -1, you are immediately moved to that numbered destination — a snake or a ladder. You may take at most one such jump per move.

Return the fewest moves needed to reach square n * n, or -1 if it cannot be reached.

LeetCode names the argument board; the harness here calls it grid.

Example 1

3635343332312526272829302423222120191314→35151617→131812111098712→153456
an ordinary squarea snake or ladder, shown as from → to
This 6 by 6 board holds 36 squares, and reaching the last one takes 4 moves. The labels are the square numbers, and they snake: the bottom row runs left to right, the row above it right to left, alternating upward, which is why a cell’s number has little to do with its position. A shaded square sends you straight to the number after the arrow, and that transfer is part of the move that landed on it rather than a move of its own.
Cells show square numbers, not the input values; a jump is written as from → to.
Input:  grid = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]
Output: 4
Explanation: Move to 2, take the ladder to 15, move to 17, take the ladder to 13, then move to 35 and finally 36.

Example 2

4312→3
an ordinary squarea snake or ladder, shown as from → to
Input:  grid = [[-1,-1],[-1,3]]
Output: 1
Explanation: The board has 4 squares, and a single roll of 3 reaches square 4 directly. The ladder on square 2 is never needed.

Example 3

78965→94→812→83→9
an ordinary squarea snake or ladder, shown as from → to
Input:  grid = [[-1,-1,-1],[-1,9,8],[-1,8,9]]
Output: 1
Explanation: A roll of 2 from square 1 lands on square 3, which holds a ladder to square 9 — the finish. The ladder is part of that one move, not a second one.

Constraints

  • 2 <= grid.length == grid[i].length <= 20
  • grid[i][j] is -1 or in the range [1, n * n]
  • The square numbered 1 and the square numbered n * n do not hold a snake or ladder
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every move costs the same, one, whatever number you roll. That is what settles the method: the cheapest route through a graph with uniform edge costs is found by exploring outward in rings of equal distance, so the first time square n * n is reached, it is reached in the fewest moves.

Almost all the difficulty is the numbering, not the search. Converting a square number to a row and column is where solutions break: the rows run bottom to top, and every other row runs right to left. Write that conversion as its own function and test it on the corners before anything else.

The second subtlety is that a snake or ladder is not an extra move. Landing on square 2 and being carried to 15 is one move, not two. So the destination replaces the landing square before the distance is recorded.

The third is that you may not chain jumps: if square 15 also held a ladder, you would not follow it. Applying the jump exactly once, at the moment of landing, gives that for free — as long as you do not re-apply it when the destination is later dequeued.

Approach

  1. Write a helper turning a square number into (row, col). With n rows, square x is at distance x - 1 from the start; the row from the bottom is (x - 1) / n and the offset along it is (x - 1) % n.
  2. The array row index is n - 1 - (row from bottom). If the row from the bottom is even the column is the offset; if odd it is n - 1 - offset.
  3. Explore from square 1 with a distance of 0, keeping a visited set of square numbers.
  4. For each square, consider the six next squares that are still on the board. For each, look up its cell: if the value is not -1, the real destination is that value.
  5. If the destination has not been visited, record it at one more move and continue. Return that distance the moment the destination is n * n.
  6. If the exploration runs out, return -1.

Walkthrough

numbering a 3 by 3 board

   array rows            square numbers
   row 0  [a b c]           7 8 9
   row 1  [d e f]           6 5 4
   row 2  [g h i]           1 2 3

   square 1 -> (x-1) = 0, row from bottom 0, offset 0
               even row, so col 0; array row 3-1-0 = 2
               cell (2,0)   correct
   square 4 -> (x-1) = 3, row from bottom 1, offset 0
               ODD row, so col = 3-1-0 = 2; array row 1
               cell (1,2)   correct
   square 9 -> (x-1) = 8, row from bottom 2, offset 2
               even row, col 2; array row 0
               cell (0,2)   correct

search on grid = [[-1,-1,-1],[-1,9,8],[-1,8,9]]
   from square 1, the reachable squares are 2..7
      2 -> cell (2,1) = 8   -> carried to 8
      3 -> cell (2,2) = 9   -> carried to 9  = n*n, DONE
   answer 1

   note 3 is reached and immediately carried to 9; that
   is still one move, not two.

Complexity

  • Time — O(n^2): each square is enqueued at most once and examines six successors.
  • Space — O(n^2): the visited set and the frontier.

Common Pitfalls

  • Getting the boustrophedon conversion wrong. Test it on squares 1, n, n + 1 and n * n before trusting the search.
  • Counting a snake or ladder as a second move. It is part of the move that landed on it.
  • Following a chain of jumps. At most one jump per move, so do not re-apply the lookup at the destination.
  • Marking the landing square as visited instead of the destination, which lets the same destination be queued repeatedly.
  • Exploring with a depth-first walk or a cost-ordered queue. Every move costs 1, so ring-by-ring exploration is both correct and simpler here.

Full Solution — all languages

class Solution:
    def snakesAndLadders(self, grid):
        from collections import deque

        n = len(grid)
        target = n * n

        def cell(square):
            # Rows run bottom to top; alternate rows run right to left.
            row_from_bottom, along = divmod(square - 1, n)
            r = n - 1 - row_from_bottom
            c = along if row_from_bottom % 2 == 0 else n - 1 - along
            return r, c

        queue = deque([(1, 0)])
        seen = {1}

        while queue:
            square, moves = queue.popleft()

            for roll in range(1, 7):
                nxt = square + roll
                if nxt > target:
                    break

                r, c = cell(nxt)
                # A snake or ladder is part of THIS move, not an extra one.
                if grid[r][c] != -1:
                    nxt = grid[r][c]

                if nxt == target:
                    return moves + 1

                if nxt not in seen:
                    seen.add(nxt)
                    queue.append((nxt, moves + 1))

        return -1
SensAI
Beta
Tap the mic to stop voice mode