BudiBadu Logo

Riverside Power Grid Check

Array Easy 2 views
Like14

The riverside utility district monitors electrical substations (0 to n-1) linked by bidirectional power lines. When crews start a safety check from an Origin, they follow the lines to inspect every reachable neighbor. Your goal in Riverside Power Grid Check is to find the total count of unique substations verified during a single tour starting from that home base.

The "secret sauce" here is Network Exploration (Traversal). Use BFS or DFS to branch out from the origin substation and mark each new node you hit. Disconnected sections of the grid remain unchecked and are excluded from your tally. Duplicate lines or self-loops in the engineering map shouldn't change the final result—you only count each unique substation once. Return the total coverage as a single integer. This helps the district ensure all reachable infrastructure is safe while identifying exactly which pockets of the grid are currently isolated from the main supply line!

When the task involves connectivity or route cost, build adjacency carefully and guard against revisiting stale states. Use a visited or best-distance structure to avoid repeated work, and ensure unreachable scenarios return the required fallback value instead of partial traversal results.

Examples

Example 1
Input
n = 6, lines = [[0,1],[1,2],[0,2],[3,4]], origin = 3
Output
2
Explanation

Only substations 3 and 4 are reachable from the origin segment.

Example 2
Input
n = 5, lines = [[0,1],[1,2],[2,3],[3,4]], origin = 0
Output
5
Explanation

The crew moves sequentially across each line and inspects every substation.

Example 3
Input
n = 4, lines = [], origin = 2
Output
1
Explanation

With no power lines connected, only the origin substation is inspected.

Algorithm Flow

Recommendation Algorithm Flow for Riverside Power Grid Check - Budibadu
Recommendation Algorithm Flow for Riverside Power Grid Check - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int power_grid_coverage(int n, int[][] lines, int origin) {
        Map<Integer, List<Integer>> adj = new HashMap<>();
        for (int[] line : lines) {
            adj.computeIfAbsent(line[0], k -> new ArrayList<>()).add(line[1]);
            adj.computeIfAbsent(line[1], k -> new ArrayList<>()).add(line[0]);
        }

        if (!adj.containsKey(origin)) return 1;

        Set<Integer> visited = new HashSet<>();
        Queue<Integer> queue = new LinkedList<>();
        
        visited.add(origin);
        queue.offer(origin);
        
        while (!queue.isEmpty()) {
            int u = queue.poll();
            if(adj.containsKey(u)) {
                for (int v : adj.get(u)) {
                    if (visited.add(v)) {
                        queue.offer(v);
                    }
                }
            }
        }
        
        return visited.size();
    }
}