Approach
Breadth-first search
For Modify Graph Edge Weights, 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
- 81 lines of Java from the credited upstream file 2699.java.
- The implementation visibly relies on sequence storage, work queue.
- 7 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[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) {3 final int MAX = 2_000_000_000;4 List<Pair<Integer, Integer>>[] graph = new List[n];5 6 for (int i = 0; i < n; i++)7 graph[i] = new ArrayList<>();8 9 for (int[] edge : edges) {10 final int u = edge[0];11 final int v = edge[1];12 final int w = edge[2];13 if (w == -1)14 continue;15 graph[u].add(new Pair<>(v, w));16 graph[v].add(new Pair<>(u, w));17 }18 19 int distToDestination = dijkstra(graph, source, destination);20 if (distToDestination < target)21 return new int[0][];22 if (distToDestination == target) {23 24 for (int[] edge : edges)25 if (edge[2] == -1)26 edge[2] = MAX;27 return edges;28 }29 30 for (int i = 0; i < edges.length; ++i) {31 final int u = edges[i][0];32 final int v = edges[i][1];33 final int w = edges[i][2];34 if (w != -1)35 continue;36 edges[i][2] = 1;37 graph[u].add(new Pair<>(v, 1));38 graph[v].add(new Pair<>(u, 1));39 distToDestination = dijkstra(graph, source, destination);40 if (distToDestination <= target) {41 edges[i][2] += target - distToDestination;42 43 for (int j = i + 1; j < edges.length; ++j)44 if (edges[j][2] == -1)45 edges[j][2] = MAX;46 return edges;47 }48 }49 50 return new int[0][];51 }52 53 private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) {54 int[] dist = new int[graph.length];55 Arrays.fill(dist, Integer.MAX_VALUE);56 57 dist[src] = 0;58 Queue<Pair<Integer, Integer>> minHeap =59 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {60 { offer(new Pair<>(dist[src], src)); } 61 };62 63 while (!minHeap.isEmpty()) {64 final int d = minHeap.peek().getKey();65 final int u = minHeap.poll().getValue();66 if (d > dist[u])67 continue;68 for (Pair<Integer, Integer> pair : graph[u]) {69 final int v = pair.getKey();70 final int w = pair.getValue();71 if (d + w < dist[v]) {72 dist[v] = d + w;73 minHeap.offer(new Pair<>(dist[v], v));74 }75 }76 }77 78 return dist[dst];79 }80}81