File tree 1 file changed +44
-0
lines changed 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+ from collections import deque
3
+
4
+ class Solution :
5
+ def snakesAndLadders (self , board : List [List [int ]]) -> int :
6
+ n : int = len (board )
7
+
8
+ # Helper to map a square label s (1-based) to (row, col) in Boustrophedon layout
9
+ def get_coordinates (s : int ) -> tuple [int , int ]:
10
+ quot , rem = divmod (s - 1 , n )
11
+ row = n - 1 - quot
12
+ if quot % 2 == 0 :
13
+ col = rem
14
+ else :
15
+ col = n - 1 - rem
16
+ return row , col
17
+
18
+ # BFS queue will store (current_square, moves_taken)
19
+ queue : deque [tuple [int , int ]] = deque ()
20
+ queue .append ((1 , 0 ))
21
+
22
+ visited : set [int ] = set ([1 ])
23
+ target : int = n * n
24
+
25
+ while queue :
26
+ square , moves = queue .popleft ()
27
+
28
+ # Try all possible dice rolls from 1 to 6
29
+ for nxt in range (square + 1 , min (square + 6 , target ) + 1 ):
30
+ r , c = get_coordinates (nxt )
31
+
32
+ # If there's a snake/ladder at board[r][c], we must take it
33
+ dest : int = board [r ][c ] if board [r ][c ] != - 1 else nxt
34
+
35
+ # If we reached the final square, return moves + 1 immediately
36
+ if dest == target :
37
+ return moves + 1
38
+
39
+ if dest not in visited :
40
+ visited .add (dest )
41
+ queue .append ((dest , moves + 1 ))
42
+
43
+ # If BFS completes without reaching n^2, it's unreachable
44
+ return - 1
You can’t perform that action at this time.
0 commit comments