Skip to content

Commit 3b5aa34

Browse files
committed
Sync LeetCode submission Runtime - 159 ms (75.48%), Memory - 18.1 MB (64.41%)
1 parent c521936 commit 3b5aa34

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

1171-shortest-path-in-binary-matrix/solution.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
# Approach 1: Breadth First Search, overwrite input
1+
# Approach 1: Breadth-first Search (BFS), Overwriting Input
22

3-
# Time: O(N)
4-
# Space: O(N)
3+
# n = no. of cells
4+
# Time: O(n)
5+
# Space: O(n)
56

6-
import collections
7+
from collections import deque
78

89
class Solution:
910
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
@@ -15,17 +16,19 @@ def get_neighbors(row, col):
1516
for row_diff, col_diff in directions:
1617
new_row = row + row_diff
1718
new_col = col + col_diff
18-
if not(0 <= new_row <= max_row and 0 <= new_col <= max_col):
19+
20+
if not (0 <= new_row <= max_row and 0 <= new_col <= max_col):
1921
continue
2022
if grid[new_row][new_col] != 0:
2123
continue
22-
2324
yield (new_row, new_col)
2425

26+
# Check that first and last cells are open
2527
if grid[0][0] != 0 or grid[max_row][max_col] != 0:
2628
return -1
2729

28-
queue = collections.deque()
30+
# Set up BFS
31+
queue = deque()
2932
queue.append((0, 0))
3033
grid[0][0] = 1
3134

@@ -34,6 +37,7 @@ def get_neighbors(row, col):
3437
distance = grid[row][col]
3538
if (row, col) == (max_row, max_col):
3639
return distance
40+
3741
for neighbor_row, neighbor_col in get_neighbors(row, col):
3842
grid[neighbor_row][neighbor_col] = distance + 1
3943
queue.append((neighbor_row, neighbor_col))

0 commit comments

Comments
 (0)