Approach
Breadth-first search
For Find Edges in Shortest Paths, 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
- 60 lines of Java from the credited upstream file 3123.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 3 public boolean[] findAnswer(int n, int[][] edges) {4 boolean[] ans = new boolean[edges.length];5 List<Pair<Integer, Integer>>[] graph = new List[n];6 Arrays.setAll(graph, i -> new ArrayList<>());7 8 for (int[] edge : edges) {9 final int u = edge[0];10 final int v = edge[1];11 final int w = edge[2];12 graph[u].add(new Pair<>(v, w));13 graph[v].add(new Pair<>(u, w));14 }15 16 int[] from0 = dijkstra(graph, 0);17 int[] from1 = dijkstra(graph, n - 1);18 19 for (int i = 0; i < edges.length; ++i) {20 final int u = edges[i][0];21 final int v = edges[i][1];22 final int w = edges[i][2];23 ans[i] = from0[u] + w + from1[v] == from0[n - 1] || 24 from0[v] + w + from1[u] == from0[n - 1];25 }26 27 return ans;28 }29 30 private static int MAX = 1_000_000_000;31 32 private int[] dijkstra(List<Pair<Integer, Integer>>[] graph, int src) {33 int[] dist = new int[graph.length];34 Arrays.fill(dist, MAX);35 36 dist[src] = 0;37 Queue<Pair<Integer, Integer>> minHeap =38 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {39 { offer(new Pair<>(dist[src], src)); } 40 };41 42 while (!minHeap.isEmpty()) {43 final int d = minHeap.peek().getKey();44 final int u = minHeap.poll().getValue();45 if (d > dist[u])46 continue;47 for (Pair<Integer, Integer> pair : graph[u]) {48 final int v = pair.getKey();49 final int w = pair.getValue();50 if (d + w < dist[v]) {51 dist[v] = d + w;52 minHeap.offer(new Pair<>(dist[v], v));53 }54 }55 }56 57 return dist;58 }59};60