Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Bus Routes

Hard · Graphs · Asked at Google, Amazon, Uber, Microsoft

Each bus repeats its route forever, visiting its list of stops in a loop. You start at stop S (not on a bus) and want to reach stop T. Print the minimum number of buses you must take, or -1 if it is impossible (0 if S = T).

Input

First line: n (number of buses). Next n lines: m followed by the m stops of that bus. Last line: S T.

Output

The minimum number of buses, or -1.

Constraints

BFS over buses, not stops. Map every stop to the buses that visit it. Start with all buses through S at distance 1; from a bus, every stop on it leads to all buses through that stop. Mark buses (and stops) as visited so each is expanded once.

Example 1

Input

2
3 1 2 7
3 3 6 7
1 6

Output

2

Example 2

Input

5
2 7 12
3 4 5 15
1 6
2 15 19
3 9 12 13
15 12

Output

-1

Hints

  1. What you count is buses taken, not stops visited.
  2. Two buses are "connected" if they share a stop.
  3. BFS over buses, starting from every bus that passes S.

Approach

Build a map stop → list of buses. If S = T the answer is 0. Put every bus through S in the queue with distance 1. When processing a bus, look at each of its stops: if it is T, return the bus's distance; otherwise, if the stop is new, enqueue every unvisited bus through it with distance + 1. Marking stops as processed ensures each stop's bus list is scanned once, so the total work is linear in the input.

Complexity: O(total stops) time · O(total stops) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<vector<int>> routes(n);
    unordered_map<int, vector<int>> byStop;
    for (int b = 0; b < n; b++) {
        int m;
        cin >> m;
        routes[b].resize(m);
        for (auto &x : routes[b]) {
            cin >> x;
            byStop[x].push_back(b);
        }
    }
    int S, T;
    cin >> S >> T;
    if (S == T) {
        cout << 0 << "\n";
        return 0;
    }
    vector<int> dist(n, -1);
    queue<int> q;
    for (int b : byStop[S]) {
        dist[b] = 1;
        q.push(b);
    }
    unordered_set<int> seenStop = {S};
    while (!q.empty()) {
        int b = q.front();
        q.pop();
        for (int x : routes[b]) {
            if (x == T) {
                cout << dist[b] << "\n";
                return 0;
            }
            if (!seenStop.insert(x).second) continue;
            for (int nb : byStop[x])
                if (dist[nb] < 0) {
                    dist[nb] = dist[b] + 1;
                    q.push(nb);
                }
        }
    }
    cout << -1 << "\n";
    return 0;
}

Python solution

import sys
from collections import defaultdict, deque

data = list(map(int, sys.stdin.read().split()))
n = data[0]
p = 1
routes = []
by_stop = defaultdict(list)
for b in range(n):
    m = data[p]
    stops = data[p + 1 : p + 1 + m]
    p += 1 + m
    routes.append(stops)
    for x in stops:
        by_stop[x].append(b)
S, T = data[p], data[p + 1]


def solve():
    if S == T:
        return 0
    dist = [-1] * n
    q = deque()
    for b in by_stop.get(S, []):
        dist[b] = 1
        q.append(b)
    seen = {S}
    while q:
        b = q.popleft()
        for x in routes[b]:
            if x == T:
                return dist[b]
            if x in seen:
                continue
            seen.add(x)
            for nb in by_stop[x]:
                if dist[nb] < 0:
                    dist[nb] = dist[b] + 1
                    q.append(nb)
    return -1


print(solve())

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        int[][] routes = new int[n][];
        HashMap<Integer, List<Integer>> byStop = new HashMap<>();
        for (int b = 0; b < n; b++) {
            in.nextToken();
            int m = (int) in.nval;
            routes[b] = new int[m];
            for (int j = 0; j < m; j++) {
                in.nextToken();
                routes[b][j] = (int) in.nval;
                byStop.computeIfAbsent(routes[b][j], k -> new ArrayList<>()).add(b);
            }
        }
        in.nextToken();
        int S = (int) in.nval;
        in.nextToken();
        int T = (int) in.nval;
        if (S == T) {
            System.out.println(0);
            return;
        }
        int[] dist = new int[n];
        Arrays.fill(dist, -1);
        ArrayDeque<Integer> q = new ArrayDeque<>();
        for (int b : byStop.getOrDefault(S, new ArrayList<>())) {
            dist[b] = 1;
            q.add(b);
        }
        HashSet<Integer> seen = new HashSet<>();
        seen.add(S);
        while (!q.isEmpty()) {
            int b = q.poll();
            for (int x : routes[b]) {
                if (x == T) {
                    System.out.println(dist[b]);
                    return;
                }
                if (!seen.add(x)) continue;
                for (int nb : byStop.get(x))
                    if (dist[nb] < 0) {
                        dist[nb] = dist[b] + 1;
                        q.add(nb);
                    }
            }
        }
        System.out.println(-1);
    }
}

Solve Bus Routes online · All practice problems