Skip to content

Commit

Permalink
Create 909-Snakes-and-Ladders.py
Browse files Browse the repository at this point in the history
  • Loading branch information
neetcode-gh authored Dec 31, 2021
1 parent 10ebd56 commit 0b793e1
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 909-Snakes-and-Ladders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
length = len(board)
board.reverse()
def intToPos(square):
r = (square - 1) // length
c = (square - 1) % length
if r % 2:
c = length - 1 - c
return [r, c]

q = deque()
q.append([1, 0]) # [square, moves]
visit = set()
while q:
square, moves = q.popleft()
for i in range(1, 7):
nextSquare = square + i
r, c = intToPos(nextSquare)
if board[r][c] != -1:
nextSquare = board[r][c]
if nextSquare == length * length:
return moves + 1
if nextSquare not in visit:
visit.add(nextSquare)
q.append([nextSquare, moves + 1])
return -1

0 comments on commit 0b793e1

Please sign in to comment.