5
public int countRestrictedPaths(int n, int[][] edges) {6
int[] dist = new int[n + 1];9
Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();10
// Create the graph from input edges11
for (int[] e : edges) {12
graph.putIfAbsent(e[0], new HashMap<>());13
graph.putIfAbsent(e[1], new HashMap<>());14
graph.get(e[0]).put(e[1], e[2]);15
graph.get(e[1]).put(e[0], e[2]);17
// Single source shortest distance - something like Dijkstra's18
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (a[1] - b[1]));19
int[] base = new int[2];22
while (!pq.isEmpty()) {23
int[] currNode = pq.poll();25
for (Map.Entry<Integer, Integer> neighbour : graph.get(currNode[0]).entrySet()) {26
int node = neighbour.getKey();27
int d = neighbour.getValue() + currNode[1];28
if (node == n) continue;29
// Select only those neighbours, whose new distance is less than existing distance30
// New distance = distance of currNode from n + weight of edge between currNode and33
if (dist[node] == 0 || d < dist[node]) {34
int[] newNode = new int[2];43
return find(1, graph, n, dist);46
// This method traverses all the paths from source node to n though it's neigbours47
private int find(int node, Map<Integer, Map<Integer, Integer>> graph, int n, int[] dist) {52
// Memoization avoid computaion of common subproblems.53
if (dp[node] != -1) return dp[node];56
for (Map.Entry<Integer, Integer> neighbour : graph.get(node).entrySet()) {57
int currNode = neighbour.getKey();58
int d = dist[currNode];60
ans = (ans + find(currNode, graph, n, dist)) % 1000000007;64
return dp[node] = ans;