-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path3603-minimum-cost-path-with-alternating-directions-ii.py
More file actions
55 lines (47 loc) · 1.71 KB
/
3603-minimum-cost-path-with-alternating-directions-ii.py
File metadata and controls
55 lines (47 loc) · 1.71 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# time complexity: O(n*m)
# space complexity: O(n*M)
from heapq import heappop, heappush
from typing import List
class Solution:
def minCost(self, m: int, n: int, waitCost: List[List[int]]) -> int:
heap = [(1, 0, 0, 1)]
visited = {}
visited[(0, 0, 1 % 2)] = 1
ROW, COL = m, n
while heap:
currCost, r, c, time = heappop(heap)
if r == ROW - 1 and c == COL - 1:
return currCost
if currCost > visited.get((r, c, time % 2), float('inf')):
continue
if time % 2 == 0:
nextTime = time + 1
nextCost = currCost + waitCost[r][c]
key = (r, c, nextTime % 2)
if nextCost < visited.get(key, float('inf')):
visited[key] = nextCost
heappush(heap, (nextCost, r, c, nextTime))
else:
for dR, dC in [(0, 1), (1, 0)]:
nextR, nextC = r + dR, c + dC
if 0 <= nextR < ROW and 0 <= nextC < COL:
nextTime = time + 1
entryCost = (nextR + 1) * (nextC + 1)
nextCost = currCost + entryCost
key = (nextR, nextC, nextTime % 2)
if nextCost < visited.get(key, float('inf')):
visited[key] = nextCost
heappush(heap, (nextCost, nextR, nextC, nextTime))
return -1
m = 1
n = 2
waitCost = [[1, 2]]
print(Solution().minCost(m, n, waitCost))
m = 2
n = 2
waitCost = [[3, 5], [2, 4]]
print(Solution().minCost(m, n, waitCost))
m = 2
n = 3
waitCost = [[6, 1, 4], [3, 2, 5]]
print(Solution().minCost(m, n, waitCost))