Skip to content

Commit

Permalink
Create NumberOfWaysToReachDestination.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jun 30, 2024
1 parent 794f8a9 commit 8fd0d0c
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Graphs/NumberOfWaysToReachDestination.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
public:
int countPaths(int n, vector<vector<int>>& roads) {
int mod = (1e9 + 7);
vector<pair<int,int>> adj[n];
for(auto it: roads){
adj[it[0]].push_back({it[1], it[2]});
adj[it[1]].push_back({it[0], it[2]});
}

priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<pair<long long,int>>> pq;

vector<long long> dist(n, 1e18);
vector<int> ways(n, 0);

dist[0] = 0;
ways[0] = 1;

pq.push({0,0});


while(!pq.empty()){
long long dis = pq.top().first;
int node = pq.top().second;
pq.pop();

for(auto i : adj[node]){
int adjnode = i.first;
long long adjweight = i.second;

if(dis + adjweight < dist[adjnode]){
dist[adjnode] = adjweight + dis;
pq.push({dist[adjnode], adjnode});
// IMP
ways[adjnode] = ways[node]% mod;
//
}
else if(dis + adjweight == dist[adjnode])
{
// IMP
ways[adjnode] = (ways[adjnode] + ways[node])%mod;
//
}
}
}
return (ways[n - 1]) % mod;
}
};

0 comments on commit 8fd0d0c

Please sign in to comment.