imashutosh51

Snake and Ladder Problem

Aug 10th, 2022 (edited)
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. '''
  2. T.C O(N) ie. no. of blocks
  3. Logic:
  4. ->We will use bfs here.snl
  5.  
  6.  
  7. the firs tip is flat the 2d table to 1d just keep in mind that first row of input is the top of snake and ladder and bottom is the start ie. 1,2,3 and flat the board like 1,2,3...n*n+1
  8. '''
  9.  
  10. from collections import deque
  11. class Solution:
  12.     def snakesAndLadders(self, board):
  13.         n = len(board)
  14.  
  15.         # Step 1: Convert board to 1D array
  16.         cells = [-1] * (n * n + 1)
  17.         idx = 1
  18.         left_to_right = True
  19.  
  20.         for r in range(n - 1, -1, -1): #we are doing here because first bottom row is at end and top row is it in beginning.
  21.             for val in board[r] if left_to_right else reversed(board[r]): #if direction is left to right, we follow as it is else reverse
  22.  
  23.                 # Assign the board value to the current square number
  24.                 # val == -1  -> normal square
  25.                 # val != -1  -> snake or ladder destination
  26.                 cells[idx] = val
  27.  
  28.                 # Move to the next square number
  29.                 idx += 1
  30.  
  31.             # After finishing one row, flip the direction
  32.             # This creates the zig-zag (boustrophedon) pattern
  33.             left_to_right = not left_to_right
  34.  
  35.  
  36.         # Step 2: BFS
  37.         queue = deque([(1, 0)])  # (current square, moves)
  38.         visited = set([1])
  39.  
  40.         while queue:
  41.             curr, moves = queue.popleft()
  42.  
  43.             for next_sq in range(curr + 1, min(curr + 6, n * n) + 1):
  44.                 dest = cells[next_sq] if cells[next_sq] != -1 else next_sq
  45.  
  46.                 if dest == n * n:
  47.                     return moves + 1
  48.  
  49.                 if dest not in visited:
  50.                     visited.add(dest)
  51.                     queue.append((dest, moves + 1))
  52.  
  53.         return -1
  54.  
Advertisement
Add Comment
Please, Sign In to add comment