Skip to content

Commit 4fb05f6

Browse files
authored
Create 1091-shortest-path-in-a-binary-matrix.py
1 parent 7787277 commit 4fb05f6

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
3+
N = len(grid)
4+
q = deque([(0, 0, 1)]) # r, c, length
5+
visit = set((0, 0))
6+
direct = [[0, 1], [1, 0], [0, -1], [-1, 0],
7+
[1, 1], [-1, -1], [1, -1], [-1, 1]]
8+
while q:
9+
r, c, length = q.popleft()
10+
if (min(r, c) < 0 or max(r, c) >= N or
11+
grid[r][c]):
12+
continue
13+
if r == N - 1 and c == N - 1:
14+
return length
15+
for dr, dc in direct:
16+
if (r + dr, c + dc) not in visit:
17+
q.append((r + dr, c + dc, length + 1))
18+
visit.add((r + dr, c + dc))
19+
return -1

0 commit comments

Comments
 (0)