Minimum Moves to Reach Target with Rotations LeetCode solution in Python

1
class Solution:
2
def minimumMoves(self, grid: List[List[int]]) -> int:
3
queue, vis, n = [(0, 1, 0, 0)], {}, len(grid)
4
while queue:
5
x, y, pos, moves = queue.pop(0)
6
if x == y == n - 1 and pos == 0:
7
return moves
8
if pos == 0:
9
if y + 1 < n and grid[x][y + 1] == 0 and (x, y + 1, 0) not in vis:
10
vis[(x, y + 1, 0)] = True
11
queue.append((x, y + 1, 0, moves + 1))
12

13
if x + 1 < n and grid[x + 1][y - 1] == 0 and grid[x + 1][y] == 0:
14
if (x + 1, y - 1, 1) not in vis:
15
vis[(x + 1, y - 1, 1)] = True
16
queue.append((x + 1, y - 1, 1, moves + 1))
17
if (x + 1, y, 0) not in vis:
18
vis[(x + 1, y, 0)] = True
19
queue.append((x + 1, y, 0, moves + 1))
20
else:
21
if x + 1 < n and grid[x + 1][y] == 0 and (x + 1, y, 1) not in vis:
22
vis[(x + 1, y, 1)] = True
23
queue.append((x + 1, y, 1, moves + 1))
24
if y + 1 < n and grid[x - 1][y + 1] == grid[x][y + 1] == 0:
25
if (x - 1, y + 1, 0) not in vis:
26
vis[(x - 1, y + 1, 0)] = True
27
queue.append((x - 1, y + 1, 0, moves + 1))
28
if (x, y + 1, 1) not in vis:
29
vis[(x, y + 1, 1)] = True
30
queue.append((x, y + 1, 1, moves + 1))
31
return -1

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0