Problem solution · Java

Minimum Weighted Subgraph With the Required Paths

Minimum Weighted Subgraph With the Required Paths: 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
65 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 Minimum Weighted Subgraph With the Required Paths, 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

  • 65 lines of Java from the credited upstream file 2203.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.

Source

Code and credit

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

Full codeMinimum Weighted Subgraph With the Required Paths · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) {    List<Pair<Integer, Integer>>[] graph = new List[n];    List<Pair<Integer, Integer>>[] reversedGraph = new List[n];     for (int i = 0; i < n; ++i) {      graph[i] = new ArrayList<>();      reversedGraph[i] = new ArrayList<>();    }     for (int[] edge : edges) {      final int u = edge[0];      final int v = edge[1];      final int w = edge[2];      graph[u].add(new Pair<>(v, w));      reversedGraph[v].add(new Pair<>(u, w));    }     long[] fromSrc1 = dijkstra(graph, src1);    long[] fromSrc2 = dijkstra(graph, src2);    long[] fromDest = dijkstra(reversedGraph, dest);    long ans = MAX;     for (int i = 0; i < n; ++i) {      if (fromSrc1[i] == MAX || fromSrc2[i] == MAX || fromDest[i] == MAX)        continue;      ans = Math.min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]);    }     return ans == MAX ? -1 : ans;  }   private static long MAX = (long) 1e10;   private long[] dijkstra(List<Pair<Integer, Integer>>[] graph, int src) {    long[] dist = new long[graph.length];    Arrays.fill(dist, MAX);     dist[src] = 0;    Queue<Pair<Long, Integer>> minHeap =        new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) {          {            offer(new Pair<>(dist[src], src)); // (d, u)          }        };     while (!minHeap.isEmpty()) {      final long 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;  }} 

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 ↗