Skip to content

Commit 3637986

Browse files
authored
Create minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py
1 parent ca10a6e commit 3637986

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(m * n)
2+
# Space: O(m * n)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def minCost(self, grid):
9+
"""
10+
:type grid: List[List[int]]
11+
:rtype: int
12+
"""
13+
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
14+
R, C = len(grid), len(grid[0])
15+
dq = collections.deque([(0, 0, 0)])
16+
lookup = {(0, 0): 0}
17+
while dq:
18+
d, r, c = dq.popleft()
19+
if r == R-1 and c == C-1:
20+
return d
21+
for nd, (dr, dc) in enumerate(directions, 1):
22+
nr, nc = r+dr, c+dc
23+
cost = 1-(nd == grid[r][c])
24+
if not (0 <= nr < R and 0 <= nc < C and
25+
((nr, nc) not in lookup or d+cost < lookup[nr, nc])):
26+
continue
27+
lookup[nr, nc] = d+cost
28+
if cost:
29+
dq.append((d+cost, nr, nc))
30+
else:
31+
dq.appendleft((d, nr, nc))
32+
return -1 # never reach here

0 commit comments

Comments
 (0)