algoadvance

You are given a n x n integer matrix board where the cells are filled with either numbers or -1. The numbers in the cells represent ladders and snakes, such that:

Your task is to find the minimum number of moves required to reach the last cell, i.e., n*n starting from cell 1. You can only move forward from your current cell x to x + i where 1 <= i <= 6 (like rolling a 6-faced die). If you encounter a snake or ladder, you must move to the destination cell as represented on the board.

Clarifying Questions

  1. Format of Input and Output:
    • Input: board (list of lists of integers)
    • Output: Integer representing the minimum number of moves to reach the last cell
  2. Board Layout:
    • The board cells are numbered from 1 to n^2, starting from the bottom-left corner and alternating directions row by row.
  3. Edge Cases:
    • Ensure the board can handle n x n where n can vary.
    • Some cells may not have snakes or ladders.

Strategy

  1. Transform the Board: Convert the 2D board representation into a 1D array to simplify access to cells. The mapping is non-trivial since row directions alternate.

  2. Breadth-First Search (BFS):

    • Initialize a queue with the starting cell (cell 1).
    • At each step, simulate rolling a die (explore the next 6 possible moves).
    • Check if the destination cell is beyond the board’s maximum cell.
    • Use a visited set to avoid re-visiting cells.
    • Continue until the last cell is reached.

Code

from collections import deque

def snakes_and_ladders(board):
    n = len(board)
    
    def get_position(square):
        """Convert the square number to board coordinates"""
        quot, rem = divmod(square - 1, n)
        row = n - 1 - quot
        col = rem if row % 2 != n % 2 else n - 1 - rem
        return row, col
    
    visited = set()
    queue = deque([(1, 0)])  # (current cell, moves)
    
    while queue:
        current, moves = queue.popleft()
        for dice in range(1, 7):
            next_square = current + dice
            if next_square > n*n:
                continue
            row, col = get_position(next_square)
            if board[row][col] != -1:
                next_square = board[row][col]
            if next_square == n*n:
                return moves + 1
            if next_square not in visited:
                visited.add(next_square)
                queue.append((next_square, moves + 1))
    
    return -1

# Example Usage:
# 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]
# ]
# print(snakes_and_ladders(board))  # Output: 4

Time Complexity

Try our interview co-pilot at AlgoAdvance.com