Snakes and Ladders
Medium
Topics
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
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
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
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
- Write a helper turning a square number into
(row, col). Withnrows, squarexis at distancex - 1from the start; the row from the bottom is(x - 1) / nand the offset along it is(x - 1) % n. - 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 isn - 1 - offset. - Explore from square 1 with a distance of 0, keeping a visited set of square numbers.
- 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. - 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. - 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 + 1andn * nbefore 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 -1import java.util.*;
class Solution {
public int snakesAndLadders(int[][] grid) {
int n = grid.length;
int target = n * n;
Deque<int[]> queue = new ArrayDeque<>();
queue.add(new int[]{1, 0});
boolean[] seen = new boolean[target + 1];
seen[1] = true;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int roll = 1; roll <= 6; roll++) {
int nxt = cur[0] + roll;
if (nxt > target) break;
// Rows run bottom to top; alternate rows run right to left.
int offset = nxt - 1;
int rowFromBottom = offset / n, along = offset % n;
int r = n - 1 - rowFromBottom;
int c = rowFromBottom % 2 == 0 ? along : n - 1 - along;
if (grid[r][c] != -1) nxt = grid[r][c];
if (nxt == target) return cur[1] + 1;
if (!seen[nxt]) {
seen[nxt] = true;
queue.add(new int[]{nxt, cur[1] + 1});
}
}
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int snakesAndLadders(vector<vector<int>>& grid) {
int n = (int)grid.size();
int target = n * n;
auto cell = [&](int square) {
int offset = square - 1;
int rowFromBottom = offset / n, along = offset % n;
int r = n - 1 - rowFromBottom;
int c = rowFromBottom % 2 == 0 ? along : n - 1 - along;
return make_pair(r, c);
};
queue<pair<int, int>> q;
q.push({1, 0});
vector<bool> seen(target + 1, false);
seen[1] = true;
while (!q.empty()) {
auto cur = q.front();
q.pop();
for (int roll = 1; roll <= 6; roll++) {
int nxt = cur.first + roll;
if (nxt > target) break;
auto rc = cell(nxt);
if (grid[rc.first][rc.second] != -1) nxt = grid[rc.first][rc.second];
if (nxt == target) return cur.second + 1;
if (!seen[nxt]) {
seen[nxt] = true;
q.push({nxt, cur.second + 1});
}
}
}
return -1;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var snakesAndLadders = function(grid) {
const n = grid.length;
const target = n * n;
const cell = (square) => {
const offset = square - 1;
const rowFromBottom = Math.floor(offset / n), along = offset % n;
const r = n - 1 - rowFromBottom;
const c = rowFromBottom % 2 === 0 ? along : n - 1 - along;
return [r, c];
};
const queue = [[1, 0]];
const seen = new Set([1]);
let head = 0;
while (head < queue.length) {
const [square, moves] = queue[head++];
for (let roll = 1; roll <= 6; roll++) {
let nxt = square + roll;
if (nxt > target) break;
const [r, c] = cell(nxt);
if (grid[r][c] !== -1) nxt = grid[r][c];
if (nxt === target) return moves + 1;
if (!seen.has(nxt)) {
seen.add(nxt);
queue.push([nxt, moves + 1]);
}
}
}
return -1;
};