Approach
Breadth-first search
For Optimize Water Distribution in a Village, 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
- 47 lines of Java from the credited upstream file 1168.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, 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 minCostToSupplyWater(int n, int[] wells, int[][] pipes) {3 int ans = 0;4 List<Pair<Integer, Integer>>[] graph = new List[n + 1];5 Queue<Pair<Integer, Integer>> minHeap =6 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); 7 8 for (int i = 0; i <= n; ++i)9 graph[i] = new ArrayList<>();10 11 for (int[] pipe : pipes) {12 final int u = pipe[0];13 final int v = pipe[1];14 final int w = pipe[2];15 graph[u].add(new Pair<>(v, w));16 graph[v].add(new Pair<>(u, w));17 }18 19 20 for (int i = 0; i < n; ++i) {21 graph[0].add(new Pair<>(i + 1, wells[i]));22 minHeap.offer(new Pair<>(wells[i], i + 1));23 }24 25 Set<Integer> mst = new HashSet<>(Arrays.asList(0));26 27 while (mst.size() < n + 1) {28 final int d = minHeap.peek().getKey();29 final int u = minHeap.poll().getValue();30 if (mst.contains(u))31 continue;32 33 mst.add(u);34 ans += d;35 36 for (Pair<Integer, Integer> pair : graph[u]) {37 final int v = pair.getKey();38 final int w = pair.getValue();39 if (!mst.contains(v))40 minHeap.offer(new Pair<>(w, v));41 }42 }43 44 return ans;45 }46}47