Problem solution · Java

Modify Graph Edge Weights

Modify Graph Edge Weights: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
81 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeModify Graph Edge Weights · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) {    final int MAX = 2_000_000_000;    List<Pair<Integer, Integer>>[] graph = new List[n];     for (int i = 0; i < n; i++)      graph[i] = new ArrayList<>();     for (int[] edge : edges) {      final int u = edge[0];      final int v = edge[1];      final int w = edge[2];      if (w == -1)        continue;      graph[u].add(new Pair<>(v, w));      graph[v].add(new Pair<>(u, w));    }     int distToDestination = dijkstra(graph, source, destination);    if (distToDestination < target)      return new int[0][];    if (distToDestination == target) {      // Change the weights of negative edges to an impossible value.      for (int[] edge : edges)        if (edge[2] == -1)          edge[2] = MAX;      return edges;    }     for (int i = 0; i < edges.length; ++i) {      final int u = edges[i][0];      final int v = edges[i][1];      final int w = edges[i][2];      if (w != -1)        continue;      edges[i][2] = 1;      graph[u].add(new Pair<>(v, 1));      graph[v].add(new Pair<>(u, 1));      distToDestination = dijkstra(graph, source, destination);      if (distToDestination <= target) {        edges[i][2] += target - distToDestination;        // Change the weights of negative edges to an impossible value.        for (int j = i + 1; j < edges.length; ++j)          if (edges[j][2] == -1)            edges[j][2] = MAX;        return edges;      }    }     return new int[0][];  }   private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) {    int[] dist = new int[graph.length];    Arrays.fill(dist, Integer.MAX_VALUE);     dist[src] = 0;    Queue<Pair<Integer, Integer>> minHeap =        new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) {          { offer(new Pair<>(dist[src], src)); } // (d, u)        };     while (!minHeap.isEmpty()) {      final int d = minHeap.peek().getKey();      final int u = minHeap.poll().getValue();      if (d > dist[u])        continue;      for (Pair<Integer, Integer> pair : graph[u]) {        final int v = pair.getKey();        final int w = pair.getValue();        if (d + w < dist[v]) {          dist[v] = d + w;          minHeap.offer(new Pair<>(dist[v], v));        }      }    }     return dist[dst];  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗