Approach
Breadth-first search
For Parallel Courses III, 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
- 34 lines of Java from the credited upstream file 2050.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 minimumTime(int n, int[][] relations, int[] time) {3 List<Integer>[] graph = new List[n];4 int[] inDegrees = new int[n];5 int[] dist = time.clone();6 Arrays.setAll(graph, i -> new ArrayList<>());7 8 9 for (int[] r : relations) {10 final int u = r[0] - 1;11 final int v = r[1] - 1;12 graph[u].add(v);13 ++inDegrees[v];14 }15 16 17 Queue<Integer> q = IntStream.range(0, n)18 .filter(i -> inDegrees[i] == 0)19 .boxed()20 .collect(Collectors.toCollection(ArrayDeque::new));21 22 while (!q.isEmpty()) {23 final int u = q.poll();24 for (final int v : graph[u]) {25 dist[v] = Math.max(dist[v], dist[u] + time[v]);26 if (--inDegrees[v] == 0)27 q.offer(v);28 }29 }30 31 return Arrays.stream(dist).max().getAsInt();32 }33}34