Skip to content

Commit 317f849

Browse files
committed
Time: 8 ms (66.23%), Space: 35.1 MB (78.59%) - LeetHub
1 parent 0a85a78 commit 317f849

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public:
3+
int countPaths(int n, vector<vector<int>>& roads) {
4+
const int mod = 1e9 + 7;
5+
vector<vector<pair<int, int>>> g(n);
6+
7+
for (auto &r : roads) {
8+
g[r[0]].push_back({r[1], r[2]});
9+
g[r[1]].push_back({r[0], r[2]});
10+
}
11+
12+
// Min-heap for Dijkstra {time, node}
13+
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> pq;
14+
vector<long long> dist(n, LLONG_MAX);
15+
vector<int> ways(n, 0);
16+
17+
dist[0] = 0;
18+
ways[0] = 1;
19+
pq.push({0, 0});
20+
21+
while (!pq.empty()) {
22+
auto [curTime, u] = pq.top(); pq.pop();
23+
if (curTime > dist[u]) continue; // Ignore outdated entries
24+
for (auto &[v, time] : g[u]) {
25+
long long newTime = curTime + time;
26+
27+
if (newTime < dist[v]) {
28+
dist[v] = newTime;
29+
ways[v] = ways[u];
30+
pq.push({newTime, v});
31+
} else if (newTime == dist[v]) {
32+
ways[v] = (ways[v] + ways[u]) % mod;
33+
}
34+
}
35+
}
36+
return ways[n-1];
37+
}
38+
};

0 commit comments

Comments
 (0)