Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm: find connections between towns with a limit of train changes

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 Map

http://i.imgur.com/KEJ3I.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).

like image 351
Queequeg Avatar asked Apr 04 '12 16:04

Queequeg


1 Answers

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) where V = {all possible stations} and E = { (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 each i < j : (a_i,a_j) &in; 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]

like image 180
amit Avatar answered Oct 22 '22 08:10

amit