File tree Expand file tree Collapse file tree 1 file changed +11
-7
lines changed
1171-shortest-path-in-binary-matrix Expand file tree Collapse file tree 1 file changed +11
-7
lines changed Original file line number Diff line number Diff line change 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
89class 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 ))
You can’t perform that action at this time.
0 commit comments