BudiBadu Logo

City Bus Loop Access

Tree Medium 0 views
Like27

Technical Goal

Implement a function to determine the number of distinct stops reachable from a starting origin in a circular bus system, where certain stops are closed and cannot be visited or traversed. The system is represented as an undirected graph.

Constraints

  • n: Total number of stops (0 to n-1).
  • roads: A list of two-way connections [u, v].
  • start: The origin stop index.
  • closed_stations: A list of indices representing unreachable stops.

Rules

  • If start is in closed_stations, return 0.
  • A path is only valid if all stops on the path (including start and the target stop) are not in closed_stations.
  • Return the total count of unique accessible stops reachable via open roads.

Algorithm Flow

Recommendation Algorithm Flow for City Bus Loop Access - Budibadu
Recommendation Algorithm Flow for City Bus Loop Access - Budibadu

Best Answers

java
import java.util.*;

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