Subway in Seoul
InterviewTime limit2sMemory limit128 MB
Given up to 10 subway lines, each listing stations (0 is the start), find the minimum number of transfers to reach a destination station.
- Level
Medium6 of 10
- Topics
- Graph, BFS, Hash map, Implementation
- Solved
- No attempts yet
Problem
Mr.Goofcode, an American who has just arrived in Korea, was excited about traveling to Seoul, the capital of Korea. But when he arrived at Seoul Station on the airport railway, he was shocked by the complicated Seoul subway map. Every station in Seoul, including Seoul Station, had to be identified by numbers rather than names, and there were so many subway lines in operation that computing an optimal route was difficult.
In a panic, Mr.Goofcode asked you for help, since the two of you had long exchanged letters by email. Because Mr.Goofcode had helped you before, you decide to build a subway map application for him. But the picky Mr.Goofcode hates walking, so you want the application to minimize the number of subway transfers it suggests.
Given the subway map, find the minimum number of transfers Mr.Goofcode needs to reach his destination. The station number of Seoul Station, his starting station, is always 0.
A subway 'line' is the set of stations you can travel through on one kind of subway without transferring to another. A subway 'station' is an element of a subway line, a vertex the subway can visit. Each station can be represented as connected by edges, and the subway can move only through these edges. The subway can move in both directions.
Input
The first line gives the number of subway lines in Seoul, .
From the second line onward, for line 1 through line in order, one line gives the number of stations on that line and the station numbers that the line contains. All station numbers are distinct and are guaranteed to be integers between 0 and inclusive.
The last line of the input gives the destination station number.
Note that some subway lines may be circular. For a circular line, the input gives the station numbers it contains in the form . (See sample 2.)
Output
Output the minimum number of transfers from the starting station (Seoul Station) to the destination station on one line. If the destination cannot be reached, output -1.