Skip to content

Commit a2943b3

Browse files
authored
Create shortest-path-in-binary-matrix.py
1 parent 4bc9b9b commit a2943b3

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Time: O(n^2)
2+
# Space: O(n)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def shortestPathBinaryMatrix(self, grid):
9+
"""
10+
:type grid: List[List[int]]
11+
:rtype: int
12+
"""
13+
directions = [(-1, -1), (-1, 0), (-1, 1), \
14+
( 0, -1), ( 0, 1), \
15+
( 1, -1), ( 1, 0), ( 1, 1)]
16+
result = 0
17+
q = collections.deque([(0, 0)])
18+
while q:
19+
result += 1
20+
next_depth = collections.deque()
21+
while q:
22+
i, j = q.popleft()
23+
if 0 <= i < len(grid) and \
24+
0 <= j < len(grid[0]) and \
25+
not grid[i][j]:
26+
grid[i][j] = 1
27+
if i == len(grid)-1 and j == len(grid)-1:
28+
return result
29+
for d in directions:
30+
next_depth.append((i+d[0], j+d[1]))
31+
q = next_depth
32+
return -1

0 commit comments

Comments
 (0)