Approach
Breadth-first search
For Network Delay Time, 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
- 47 lines of Java from the credited upstream file 743.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 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 networkDelayTime(int[][] times, int n, int k) {3 List<Pair<Integer, Integer>>[] graph = new List[n];4 5 for (int i = 0; i < n; i++)6 graph[i] = new ArrayList<>();7 8 for (int[] time : times) {9 final int u = time[0] - 1;10 final int v = time[1] - 1;11 final int w = time[2];12 graph[u].add(new Pair<>(v, w));13 }14 15 return dijkstra(graph, k - 1);16 }17 18 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src) {19 int[] dist = new int[graph.length];20 Arrays.fill(dist, Integer.MAX_VALUE);21 22 dist[src] = 0;23 Queue<Pair<Integer, Integer>> minHeap =24 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {25 { offer(new Pair<>(dist[src], src)); } 26 };27 28 while (!minHeap.isEmpty()) {29 final int d = minHeap.peek().getKey();30 final int u = minHeap.poll().getValue();31 if (d > dist[u])32 continue;33 for (Pair<Integer, Integer> pair : graph[u]) {34 final int v = pair.getKey();35 final int w = pair.getValue();36 if (d + w < dist[v]) {37 dist[v] = d + w;38 minHeap.offer(new Pair<>(dist[v], v));39 }40 }41 }42 43 final int maxDist = Arrays.stream(dist).max().getAsInt();44 return maxDist == Integer.MAX_VALUE ? -1 : maxDist;45 }46}47