BudiBadu Logo

City Signal Span

Array Easy 22 views
Like1

The emergency office is designing a broadcast plan. Every intersection is labeled 0 to n-1, and you have a list of two-way roads between them. When a transmitter activates at one point, the signal spreads through every connected road. Your goal in City Signal Span is to count exactly how many unique intersections hear the message starting from a specific point.

The "secret sauce" here is Graph Connectivity (BFS/DFS). Treat the city as a graph where roads are edges. Starting from the start intersection, explore every possible path. Isolated intersections or separate road groups stay silent. Duplicate road entries reinforce connections but don't change the total, and the starting point always counts as one recipient. This approach provides a precise integer count the planners can rely on for their drill. It’s a cornerstone skill for anyone building navigation or communication software where network reach is everything!

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 = 4, roads = [[0,1],[1,2],[2,3]], start = 0
Output
4
Explanation

The signal travels along every road and covers all four intersections.

Example 2
Input
n = 6, roads = [[0,1],[1,2],[2,0],[3,4]], start = 5
Output
1
Explanation

Intersection 5 is isolated, so only the starting point receives the broadcast.

Example 3
Input
n = 5, roads = [[0,1],[1,2],[3,4]], start = 1
Output
3
Explanation

Intersections 0, 1, and 2 share a chain of roads, while 3 and 4 are separate.

Algorithm Flow

Recommendation Algorithm Flow for City Signal Span - Budibadu
Recommendation Algorithm Flow for City Signal Span - Budibadu

Best Answers

java
import java.util.*;

class Solution {
    public int city_signal_span(int n, int[][] roads, int start) {
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int[] road : roads) {
            adj.get(road[0]).add(road[1]);
            adj.get(road[1]).add(road[0]);
        }
        Set<Integer> visited = new HashSet<>();
        visited.add(start);
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            for (int neighbor : adj.get(curr)) {
                if (!visited.contains(neighbor)) {
                    visited.add(neighbor);
                    queue.add(neighbor);
                }
            }
        }
        return visited.size();
    }
}