Approach
Breadth-first search
For Number of Restricted Paths From First to Last Node, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 54 lines of Java from the credited upstream file 1786.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int countRestrictedPaths(int n, int[][] edges) {3 List<Pair<Integer, Integer>>[] graph = new List[n];4 Arrays.setAll(graph, i -> new ArrayList<>());5 6 for (int[] edge : edges) {7 final int u = edge[0] - 1;8 final int v = edge[1] - 1;9 final int w = edge[2];10 graph[u].add(new Pair<>(v, w));11 graph[v].add(new Pair<>(u, w));12 }13 14 return dijkstra(graph, 0, n - 1);15 }16 17 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) {18 final int MOD = 1_000_000_007;19 20 long[] ways = new long[graph.length];21 22 long[] dist = new long[graph.length];23 Arrays.fill(dist, Long.MAX_VALUE);24 25 ways[dst] = 1;26 dist[dst] = 0;27 28 Queue<Pair<Long, Integer>> minHeap =29 new PriorityQueue<>(Comparator.comparingLong(Pair::getKey));30 minHeap.offer(new Pair<>(dist[dst], dst));31 32 while (!minHeap.isEmpty()) {33 final long d = minHeap.peek().getKey();34 final int u = minHeap.poll().getValue();35 if (d > dist[u])36 continue;37 for (Pair<Integer, Integer> pair : graph[u]) {38 final int v = pair.getKey();39 final int w = pair.getValue();40 if (d + w < dist[v]) {41 dist[v] = d + w;42 minHeap.offer(new Pair<>(dist[v], v));43 }44 if (dist[v] < dist[u]) {45 ways[u] += ways[v];46 ways[u] %= MOD;47 }48 }49 }50 51 return (int) ways[src];52 }53}54