{x}
blog image

Snakes and Ladders

You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.

You start on square 1 of the board. In each move, starting from square curr, do the following:

  • Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].
    • This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.
  • If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.
  • The game ends when you reach the square n2.

A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any snake or ladder.

Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.

  • For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.

Return the least number of dice rolls required to reach the square n2. If it is not possible to reach the square, return -1.

 

Example 1:

Input: board = [[-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: 
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.

Example 2:

Input: board = [[-1,-1],[-1,3]]
Output: 1

 

Constraints:

  • n == board.length == board[i].length
  • 2 <= n <= 20
  • board[i][j] is either -1 or in the range [1, n2].
  • The squares labeled 1 and n2 are not the starting points of any snake or ladder.

Solution Explanation: Snakes and Ladders

The problem presents a game on an n x n board where players roll a six-sided die and move accordingly, potentially encountering snakes or ladders that change their position. The goal is to find the minimum number of dice rolls to reach the final square (n²).

Approach: Breadth-First Search (BFS)

BFS is the ideal approach due to its efficiency in finding the shortest path in an unweighted graph. The board itself can be represented as a graph where each square is a node, and edges connect a square to the squares reachable in one dice roll.

Algorithm:

  1. Initialization:

    • Start with a queue q containing the starting square (1).
    • Use a set visited (or boolean array) to track visited squares, initially containing only the starting square.
    • Initialize the moves counter to 0.
  2. Iteration:

    • While the queue is not empty:
      • Process all nodes at the current level (moves count). This ensures we explore nodes level by level, finding the shortest path first.
      • For each node curr in the queue:
        • If curr is the final square (n²), return moves.
        • For each possible dice roll outcome (next in range [curr + 1, min(curr + 6, n²)]):
          • Calculate the row and column indices (row, col) of next on the board, considering the boustrophedon order.
          • Check if a snake or ladder exists at (row, col). If so, update next to the destination.
          • If next is not visited:
            • Add next to the queue.
            • Mark next as visited.
      • Increment moves to represent moving to the next level of the BFS.
  3. No Path:

    • If the queue becomes empty before reaching the final square, it implies no path exists, so return -1.

Time and Space Complexity Analysis

  • Time Complexity: O(n²). In the worst case, we might visit every square on the board. The number of squares is n², and each square may be visited and processed once.
  • Space Complexity: O(n²). The visited set/array and the queue in the worst case can store up to n² elements (all squares on the board).

Code Implementation (Python)

from collections import deque
 
def snakesAndLadders(board):
    n = len(board)
    q = deque([1])
    visited = {1}
    moves = 0
 
    while q:
        for _ in range(len(q)):  # Process current level
            curr = q.popleft()
            if curr == n * n:
                return moves
 
            for next in range(curr + 1, min(curr + 6, n * n) + 1):
                row, col = divmod(next - 1, n)
                if row % 2:  # Odd row, reverse column order
                    col = n - 1 - col
                row = n - 1 - row  # Reverse row order
 
                next_pos = board[row][col] if board[row][col] != -1 else next
 
                if next_pos not in visited:
                    visited.add(next_pos)
                    q.append(next_pos)
 
        moves += 1
 
    return -1

This Python code directly implements the BFS algorithm described above. Other languages (Java, C++, Go, TypeScript) would follow a similar structure, only differing in syntax and data structures. The core logic remains the same for all implementations.