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:
board[i][j] = k
indicates there’s a ladder from cell (i, j)
to cell k
.-1
means there is neither a snake nor a ladder at (i, j)
.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.
board
(list of lists of integers)1
to n^2
, starting from the bottom-left corner and alternating directions row by row.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.
Breadth-First Search (BFS):
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
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?