Skip to content

Commit 4b2cf20

Browse files
author
hasibulislam999
committed
Number of Ways to Arrive at Destination problem solved
1 parent 6304fe8 commit 4b2cf20

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Title: Number of Ways to Arrive at Destination
3+
* Description: 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.
4+
* Author: Hasibul Islam
5+
* Date: 04/05/2023
6+
*/
7+
8+
/**
9+
* @param {number} n
10+
* @param {number[][]} roads
11+
* @return {number}
12+
*/
13+
const mod = 1e9 + 7;
14+
const countPaths = (n, road) => {
15+
let adj = initializeGraph(n);
16+
for (const [u, v, cost] of road) {
17+
adj[u].push([v, cost]);
18+
adj[v].push([u, cost]);
19+
}
20+
return dijkstra(n, adj, 0);
21+
};
22+
23+
const dijkstra = (n, g, source) => {
24+
// g: adjacent graph list, n: total vertices
25+
let dist = Array(n).fill(Number.MAX_SAFE_INTEGER);
26+
let ways = Array(n).fill(0);
27+
const pq = new MinPriorityQueue({ priority: (x) => x[0] * 200 + x[1] });
28+
dist[0] = 0;
29+
ways[0] = 1;
30+
pq.enqueue([0, source]);
31+
while (pq.size()) {
32+
let cur = pq.dequeue().element;
33+
let [curCost, curNode] = cur;
34+
if (dist[curNode] != curCost) continue;
35+
for (const [node, cost] of g[curNode]) {
36+
// parse neighbour node
37+
let newDis = curCost + cost;
38+
if (newDis == dist[node]) {
39+
ways[node] += ways[curNode];
40+
ways[node] %= mod;
41+
} else if (newDis < dist[node]) {
42+
dist[node] = newDis;
43+
ways[node] = ways[curNode];
44+
pq.enqueue([dist[node], node]);
45+
}
46+
}
47+
}
48+
return ways[n - 1];
49+
};
50+
51+
const initializeGraph = (n) => {
52+
let G = [];
53+
for (let i = 0; i < n; i++) {
54+
G.push([]);
55+
}
56+
return G;
57+
};

0 commit comments

Comments
 (0)