class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
def intToPos(square):
r = (square - 1) // n
c = (square - 1) % n
if r % 2 == 1:
c = n - 1 - c
r = n - 1 - r
return r, c
q = deque([(1, 0)])
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 == n * n:
return moves + 1
if nextSquare not in visit:
visit.add(nextSquare)
q.append((nextSquare, moves + 1))
return -1class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
def intToPos(square):
r = (square - 1) // n
c = (square - 1) % n
if r % 2 == 1:
c = n - 1 - c
r = n - 1 - r
return r, c
dist = [-1] * (n * n + 1)
q = deque([1])
dist[1] = 0
while q:
square = q.popleft()
for i in range(1, 7):
nextSquare = square + i
if nextSquare > n * n:
break
r, c = intToPos(nextSquare)
if board[r][c] != -1:
nextSquare = board[r][c]
if dist[nextSquare] == -1:
dist[nextSquare] = dist[square] + 1
if nextSquare == n * n:
return dist[nextSquare]
q.append(nextSquare)
return -1class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
n = len(board)
def intToPos(square):
r = (square - 1) // n
c = (square - 1) % n
if r % 2 == 1:
c = n - 1 - c
r = n - 1 - r
return r, c
q = deque([1])
board[n - 1][0] = 0
moves = 0
while q:
for _ in range(len(q)):
square = q.popleft()
for i in range(1, 7):
nextSquare = square + i
if nextSquare > n * n:
break
r, c = intToPos(nextSquare)
if board[r][c] != -1:
nextSquare = board[r][c]
if board[r][c] != 0:
if nextSquare == n * n:
return moves + 1
q.append(nextSquare)
board[r][c] = 0
moves += 1
return -1