1
+ // Runtime : 228 ms (Top 5.16 % ) | Memory : 17.50 MB (Top 5.8 % )
2
+
1
3
class Solution :
2
4
def snakesAndLadders (self , board : List [List [int ]]) -> int :
3
-
4
- # creating a borad map to loop-up the square value
5
- board_map = {}
6
- i = 1
7
- b_rev = board [::- 1 ]
8
- for d , r in enumerate (b_rev ):
9
- # reverse for even rows - here d is taken as direction
10
- if d % 2 != 0 : r = r [::- 1 ]
11
- for s in r :
12
- board_map [i ] = s
13
- i += 1
14
-
15
- # BFS Algorithm
16
- q = [(1 , 0 )] # (curr, moves)
17
- v = set ()
18
- goal = len (board ) * len (board ) # end square
19
-
5
+ n = len (board )
6
+ moves = 0
7
+ q = collections .deque ([1 ])
8
+ visited = [[False for _ in range (n )] for _ in range (n )]
9
+ visited [n - 1 ][0 ] = True
20
10
while q :
21
- curr , moves = q .pop (0 )
22
- # win situation
23
- if curr == goal : return moves
24
- # BFS on next 6 places (rolling a die)
25
- for i in range (1 , 7 ):
26
- # skip square outside board
27
- if curr + i > goal : continue
28
- # get value from mapping
29
- next_pos = curr + i if board_map [curr + i ] == - 1 else board_map [curr + i ]
30
- if next_pos not in v :
31
- v .add (next_pos )
32
- q .append ((next_pos , moves + 1 ))
33
-
11
+ size = len (q )
12
+ for i in range (size ):
13
+ currBoardVal = q .popleft ()
14
+ if currBoardVal == n * n :
15
+ return moves
16
+ for diceVal in range (1 , 7 ):
17
+ if currBoardVal + diceVal > n * n :
18
+ break
19
+ pos = self .findCoordinates (currBoardVal + diceVal , n )
20
+ row , col = pos
21
+ if not visited [row ][col ]:
22
+ visited [row ][col ] = True
23
+ if board [row ][col ] == - 1 :
24
+ q .append (currBoardVal + diceVal )
25
+ else :
26
+ q .append (board [row ][col ])
27
+ moves += 1
34
28
return - 1
35
-
29
+
30
+ def findCoordinates (self , curr : int , n : int ) -> Tuple [int , int ]:
31
+ row = n - (curr - 1 ) // n - 1
32
+ col = (curr - 1 ) % n
33
+ if row % 2 == n % 2 :
34
+ return (row , n - 1 - col )
35
+ else :
36
+ return (row , col )
37
+
0 commit comments