Skip to content

Commit 97dd6a1

Browse files
authored
Create 1976.Number-of-Ways-to-Arrive-at-Destination.cpp
1 parent 4760f7f commit 97dd6a1

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using LL = long long;
2+
using PII = pair<LL,LL>;
3+
4+
class Solution {
5+
vector<vector<LL>>adj[201];
6+
unordered_map<int,LL> Map[201];
7+
long M = 1e9+7;
8+
LL dist[201];
9+
public:
10+
int countPaths(int n, vector<vector<int>>& roads)
11+
{
12+
for (auto road: roads)
13+
{
14+
LL u = road[0], v = road[1], len = road[2];
15+
adj[u].push_back({v, len});
16+
adj[v].push_back({u, len});
17+
}
18+
19+
for (int i=0; i<n; i++)
20+
dist[i] = -1;
21+
22+
priority_queue<PII, vector<PII>, greater<>>pq;
23+
pq.push({0,0});
24+
25+
while (!pq.empty())
26+
{
27+
auto [d, c] = pq.top();
28+
pq.pop();
29+
if (dist[c]!=-1)
30+
continue;
31+
if (dist[c]==-1)
32+
dist[c] = d;
33+
34+
for (auto x: adj[c])
35+
{
36+
LL nxt = x[0], len = x[1];
37+
if (dist[nxt]!=-1) continue;
38+
pq.push({d+len, nxt});
39+
}
40+
}
41+
42+
return dfs(n-1, dist[n-1]);;
43+
}
44+
45+
LL dfs(int cur, long d)
46+
{
47+
if (d != dist[cur])
48+
return 0;
49+
if (cur==0) return 1;
50+
if (Map[cur].find(d)!=Map[cur].end())
51+
return Map[cur][d];
52+
53+
LL count = 0;
54+
for (auto x: adj[cur])
55+
{
56+
LL nxt = x[0], len = x[1];
57+
count += dfs(nxt, d-len);
58+
count %= M;
59+
}
60+
Map[cur][d] = count;
61+
return count;
62+
}
63+
64+
};

0 commit comments

Comments
 (0)