forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest-path-to-get-food.py
35 lines (32 loc) · 1018 Bytes
/
shortest-path-to-get-food.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Time: O(m * n)
# Space: O(m + n)
class Solution(object):
def getFood(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
q = []
for r in xrange(len(grid)):
for c in xrange(len(grid[0])):
if grid[r][c] == '*':
q.append((r, c))
break
result = 0
while q:
result += 1
new_q = []
for r, c in q:
for dr, dc in directions:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(grid) and
0 <= nc < len(grid[0]) and
grid[nr][nc] != 'X'):
continue
if grid[nr][nc] == '#':
return result
grid[nr][nc] = 'X'
new_q.append((nr, nc))
q = new_q
return -1