[LeetCode] Number of Ways to Arrive at Destination

1976. Number of Ways to Arrive at Destination

You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.

You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.

Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 1e9 + 7.

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
struct Info {
int f, t;
long long w;

bool operator()(Info a, Info b) {
return a.w > b.w;
}
};

class Solution {
public:
int countPaths(int n, vector<vector<int>>& roads, int m = 1e9 + 7) {
unordered_map<int, vector<pair<int, int>>> d;
unordered_map<int, pair<long long, int>> v{{0, {1ll, 1}}};
priority_queue<Info, vector<Info>, Info> pq;
for(auto& r : roads) {
d[r[0]].push_back({r[2], r[1]});
d[r[1]].push_back({r[2], r[0]});
}

for(auto& r : d[0]) {
pq.push({.f = 0, .t = r.second, .w = r.first});
}

while(!pq.empty()) {
auto info = pq.top();
pq.pop();
if(v.count(info.t)) {
if(v[info.t].first >= info.w) v[info.t].second = (v[info.t].second + v[info.f].second) % m;
continue;
}
v[info.t] = {info.w, v[info.f].second};
for(auto& r : d[info.t]) {
if(v.count(r.second)) continue;
pq.push({.f = info.t, .t = r.second, .w = info.w + r.first});
}
}

return v[n - 1].second;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/19/PS/LeetCode/number-of-ways-to-arrive-at-destination/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.