Approach
Breadth-first search
For Shortest Distance After Road Addition Queries I, 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
- 45 lines of Java from the credited upstream file 3243.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 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[] shortestDistanceAfterQueries(int n, int[][] queries) {3 int[] ans = new int[queries.length];4 int[] dist = new int[n];5 List<Integer>[] graph = new List[n];6 7 for (int i = 0; i < n; ++i) {8 dist[i] = i;9 graph[i] = new ArrayList<>();10 }11 12 for (int i = 0; i < n - 1; ++i)13 graph[i].add(i + 1);14 15 for (int i = 0; i < queries.length; ++i) {16 final int u = queries[i][0];17 final int v = queries[i][1];18 graph[u].add(v);19 if (dist[u] + 1 < dist[v]) {20 dist[v] = dist[u] + 1;21 bfs(graph, v, dist);22 }23 ans[i] = dist[n - 1];24 }25 26 return ans;27 }28 29 30 31 32 private void bfs(List<Integer>[] graph, int start, int[] dist) {33 Queue<Integer> q = new LinkedList<>(Arrays.asList(start));34 while (!q.isEmpty()) {35 final int u = q.poll();36 for (final int v : graph[u]) {37 if (dist[u] + 1 < dist[v]) {38 dist[v] = dist[u] + 1;39 q.offer(v);40 }41 }42 }43 }44}45