Skip to content
Advertisement

How would you find the shortest path from a collection of lists representing train lines?

So I have four “train lines” represented as lists:

JavaScript

Essentially, each letter serves as a “station”. If a station appears on multiple lines, you can transfer from one line to another, similar to many underground city transit systems. For example, the shortest path from “a” to “h” would be [“a”, “b”, “h”] because you can go from “a” to “b” in line1, transfer to line4, and then move from “b” to “h”.

I wish to find a simple way to find the shortest path given an origin and destination point. My current solution is to convert the lines into a graph by finding the neighboring stations of a station and pairing them with that station.

JavaScript

I then found a shortest path function on this website that outputs the shortest path from a graph input.

JavaScript

I want to avoid the step of creating a graph altogether and derive the shortest path just from the four lists. Can someone help me out?

Advertisement

Answer

I implemented a heuristic and brutal-force algorithm to solve the problem with pure Python functions.

JavaScript

The graph algorithms should certainly be favoured once the complexity of the problem increased….

P.S. My results are identical to the results from @Alain T.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement