Skip to content

Commit c34bbc3

Browse files
authored
Create 1976. Number of Ways to Arrive at Destination (#749)
2 parents 33a38a9 + 2d28be2 commit c34bbc3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public:
3+
vector<vector<pair<int,long long>>>graph;
4+
5+
int countPaths(int n, vector<vector<int>>& roads) {
6+
7+
graph.resize(n);
8+
9+
for(vector<int>road : roads){
10+
int u = road[0], v = road[1], time = road[2];
11+
graph[u].push_back({v,time});
12+
graph[v].push_back({u,time});
13+
}
14+
15+
vector<long long>dist(n, LLONG_MAX);
16+
vector<int>ways(n, 0);
17+
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
18+
19+
dist[0] = 0;
20+
ways[0] = 1;
21+
pq.push({0, 0});
22+
23+
while(!pq.empty()){
24+
auto [currTime, node] = pq.top();
25+
pq.pop();
26+
27+
if(currTime > dist[node]){
28+
continue;
29+
}
30+
31+
for(auto [nextNode, time] : graph[node]){
32+
long long newTime = time + currTime;
33+
if(newTime < dist[nextNode]){
34+
dist[nextNode] = newTime;
35+
ways[nextNode] = ways[node];
36+
pq.push({newTime, nextNode});
37+
}else if(newTime == dist[nextNode]){
38+
ways[nextNode] = (ways[nextNode] + ways[node]) % 1000000007;
39+
}
40+
}
41+
}
42+
43+
return ways[n - 1];
44+
}
45+
};

0 commit comments

Comments
 (0)