|
| 1 | +from collections import deque |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def __init__(self): |
| 6 | + self.n = 0 |
| 7 | + |
| 8 | + def __get_coordinates(self, position: int) -> tuple[int, int]: |
| 9 | + row = (position - 1) // self.n |
| 10 | + col = (position - 1) % self.n |
| 11 | + if row % 2 == 1: |
| 12 | + col = self.n - 1 - col |
| 13 | + return self.n - 1 - row, col |
| 14 | + |
| 15 | + def snakesAndLadders(self, board: list[list[int]]) -> int: |
| 16 | + self.n = len(board) |
| 17 | + queue = deque([(1, 0)]) # (position, moves) |
| 18 | + visited = {1} |
| 19 | + while queue: |
| 20 | + position, moves = queue.popleft() |
| 21 | + if position == self.n * self.n: |
| 22 | + return moves |
| 23 | + for move in range(1, 7): |
| 24 | + new_position = position + move |
| 25 | + if new_position > self.n * self.n: |
| 26 | + continue |
| 27 | + row, col = self.__get_coordinates(new_position) |
| 28 | + if board[row][col] != -1: |
| 29 | + new_position = board[row][col] |
| 30 | + if new_position not in visited: |
| 31 | + queue.append((new_position, moves + 1)) |
| 32 | + visited.add(new_position) |
| 33 | + return -1 |
| 34 | + |
| 35 | + |
| 36 | +def main(): |
| 37 | + board = [[-1, -1, -1, -1, -1, -1], |
| 38 | + [-1, -1, -1, -1, -1, -1], |
| 39 | + [-1, -1, -1, -1, -1, -1], |
| 40 | + [-1, 35, -1, -1, 13, -1], |
| 41 | + [-1, -1, -1, -1, -1, -1], |
| 42 | + [-1, 15, -1, -1, -1, -1]] |
| 43 | + assert Solution().snakesAndLadders(board) == 4 |
| 44 | + |
| 45 | + board = [[-1, -1], |
| 46 | + [-1, 3]] |
| 47 | + assert Solution().snakesAndLadders(board) == 1 |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + main() |
0 commit comments