Train Ride - Miscellaneous / Composite Patterns

This problem could be much clearer with some visuals

Good explanation for Union Find above:

I think this is best solved with a Dijkstra in which each line is treated like a vertex.
// Treat each line as a vertex in a Dijkstra. The edges are the connections.
// Add each line and its implicit cost to the unvisited set.
// Select the unvisited line with lowest cost (i.e. lowest number)
// Check if it has a station that matches the target.
// If not, add all the lines that it connects to the unvisited set.
// removed selected line from unvisited set.
// Repeat