#C8684. Minimum Buses to Destination

    ID: 52693 Type: Default 1000ms 256MiB

Minimum Buses to Destination

Minimum Buses to Destination

You are given a list of bus routes. Each bus route is represented as a list of stops that the bus visits in sequence.

Your task is to determine the minimum number of buses you must take to travel from the source stop to the target stop. If it is not possible to reach the target stop, output -1.

The problem can be modeled as a graph problem where the nodes are bus stops and an edge exists between stops that are on the same bus route. A Breadth First Search (BFS) approach can be used to determine the shortest path in terms of number of buses taken.

More formally, given a set of bus routes \(R_1, R_2, \ldots, R_n\), find the minimum number of routes needed such that starting from source you can reach target by transferring between routes. If \(source = target\) then the answer is \(0\).

inputFormat

The input is given via stdin and has the following format:

N S T
K1 stop1 stop2 ... stopK1
K2 stop1 stop2 ... stopK2
...
KN stop1 stop2 ... stopKN

Where:

  • N is the number of bus routes.
  • S is the source bus stop.
  • T is the target bus stop.
  • For each bus route, the first integer Ki denotes the number of stops in that route, followed by Ki integers representing the stops in that route.

outputFormat

Output a single integer via stdout representing the minimum number of buses required to reach the target stop from the source stop. If there is no way to reach the destination, output -1.

## sample
2 1 6
3 1 2 7
3 3 6 7
2

</p>