What algorithm would you use to create an application that given appropriate data (list of cities, train routes, train stations) is capable of returning a list of connection between any two user-selected cities? The application has to choose only those connections that fall into the limit of accepted train-changes.
Example: I ask the application which train to take if I need to travel from Paris to Moscow with max. 1 stop/switch – the application returns a route: Train 1 (Paris-Berlin) -> Train 2 (Berlin->Moscow) (No direct connection exists).
Graphical example 
https://i.stack.imgur.com/NSP9y.png
If I ask the system about possible connections from Town A to Town G I get a response:
- Brown Line (0 switches = direct)
- Brown Line to Town B / Orange Line to Town G (1 switch)
- Brown Line to Town B / Orange Line to Town D / Red Line to G (2 switch)
- … all other possibilities
And thouh the 2nd and 3rd options are shorter than the 1st, it’s the 1st that should have priority (since no train-switching is involved).
Assuming the only thing important is “number of stops/switches”, then the problem is actually finding a shortest path in an unweighted directed graph.
The graph model is
G = (V,E)whereV = {all possible stations}andE = { (u,v) | there is a train/route from station u to station v }Note: let’s say you have a train which starts at a_0, and paths through a_1, a_2,…a_n: then E will contain:
(a_0,a_1),(a_0,a_2),..,(a_0,a_n)and also(a_1,a_2),(a_1,a_3),...formally: for eachi < j: (a_i,a_j) ∈ E.BFS solves this problem, and is both complete [always finds a solution if there is one] and optimal [finds the shortest path].
If the edges [routes] are weighted, something like dijkstra’s algorithm will be needed instead.
If you want a list of all possible routes, Iterative-Deepening DFS could be used, without maintaining a visited set, and print all the paths found to the target up to the relevant depth. [BFS fails to return all paths with the counter example of a clique]