Skip to content

Commit a084cf9

Browse files
authored
Create number-of-ways-to-arrive-at-destination.py
1 parent 70144a1 commit a084cf9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|),
2+
# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
3+
# Space: O(|E| + |V|) = O(|E|)
4+
5+
import heapq
6+
7+
8+
class Solution(object):
9+
def countPaths(self, n, roads):
10+
"""
11+
:type n: int
12+
:type roads: List[List[int]]
13+
:rtype: int
14+
"""
15+
MOD = 10**9+7
16+
17+
def dijkstra(adj, start, target):
18+
best = collections.defaultdict(lambda:float("inf"))
19+
best[start] = 0
20+
min_heap = [(0, start)]
21+
dp = [0]*(len(adj)) # modified, add dp to keep number of ways
22+
dp[0] = 1
23+
while min_heap:
24+
curr, u = heapq.heappop(min_heap)
25+
if best[u] < curr:
26+
continue
27+
if u == target: # modified, early return
28+
break
29+
for v, w in adj[u]:
30+
if v in best and best[v] <= curr+w:
31+
if best[v] == curr+w: # modified, update number of ways in this minimal time
32+
dp[v] = (dp[v]+dp[u])%MOD
33+
continue
34+
dp[v] = dp[u] # modified, init number of ways in this minimal time
35+
best[v] = curr+w
36+
heapq.heappush(min_heap, (curr+w, v))
37+
return dp[target]
38+
39+
adj = [[] for i in xrange(n)]
40+
for u, v, w in roads:
41+
adj[u].append((v, w))
42+
adj[v].append((u, w))
43+
return dijkstra(adj, 0, n-1)

0 commit comments

Comments
 (0)