Skip to content

Commit 4b7a8ad

Browse files
authored
Update minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py
1 parent 7a59178 commit 4b7a8ad

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

Python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ def minCost(self, grid):
1313
"""
1414
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
1515
def a_star(grid, b, t):
16-
R, C = len(grid), len(grid[0])
1716
f, dh = 0, 1
1817
closer, detour = [b], []
1918
lookup = set()
@@ -29,7 +28,7 @@ def a_star(grid, b, t):
2928
lookup.add(b)
3029
for nd, (dr, dc) in enumerate(directions, 1):
3130
nb = (b[0]+dr, b[1]+dc)
32-
if not (0 <= nb[0] < R and 0 <= nb[1] < C and nb not in lookup):
31+
if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and nb not in lookup):
3332
continue
3433
(closer if nd == grid[b[0]][b[1]] else detour).append(nb)
3534
return -1
@@ -47,25 +46,22 @@ def minCost(self, grid):
4746
:rtype: int
4847
"""
4948
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
50-
R, C = len(grid), len(grid[0])
51-
b, t = (0, 0), (R-1, C-1)
49+
b, t = (0, 0), (len(grid)-1, len(grid[0])-1)
5250
dq = collections.deque([(b, 0)])
53-
lookup = {b: 0}
51+
lookup = set()
5452
while dq:
5553
b, d = dq.popleft()
5654
if b == t:
5755
return d
58-
if lookup[b] < d:
56+
if b in lookup:
5957
continue
58+
lookup.add(b)
6059
for nd, (dr, dc) in enumerate(directions, 1):
6160
nb = (b[0]+dr, b[1]+dc)
62-
cost = 1 if nd != grid[b[0]][b[1]] else 0
63-
if not (0 <= nb[0] < R and 0 <= nb[1] < C and
64-
(nb not in lookup or lookup[nb] > d+cost)):
61+
if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and nb not in lookup):
6562
continue
66-
lookup[nb] = d+cost
67-
if not cost:
63+
if nd == grid[b[0]][b[1]]:
6864
dq.appendleft((nb, d))
6965
else:
70-
dq.append((nb, d+cost))
66+
dq.append((nb, d+1))
7167
return -1 # never reach here

0 commit comments

Comments
 (0)