Skip to content

Commit 0b793e1

Browse files
authored
Create 909-Snakes-and-Ladders.py
1 parent 10ebd56 commit 0b793e1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

909-Snakes-and-Ladders.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def snakesAndLadders(self, board: List[List[int]]) -> int:
3+
length = len(board)
4+
board.reverse()
5+
def intToPos(square):
6+
r = (square - 1) // length
7+
c = (square - 1) % length
8+
if r % 2:
9+
c = length - 1 - c
10+
return [r, c]
11+
12+
q = deque()
13+
q.append([1, 0]) # [square, moves]
14+
visit = set()
15+
while q:
16+
square, moves = q.popleft()
17+
for i in range(1, 7):
18+
nextSquare = square + i
19+
r, c = intToPos(nextSquare)
20+
if board[r][c] != -1:
21+
nextSquare = board[r][c]
22+
if nextSquare == length * length:
23+
return moves + 1
24+
if nextSquare not in visit:
25+
visit.add(nextSquare)
26+
q.append([nextSquare, moves + 1])
27+
return -1

0 commit comments

Comments
 (0)