Search code examples
pythonnetwork-programmingpath-finding

How to obtain a path we are currently "on" the graph while knowing all graph nodes and weights?


I have a network composed of nodes and edges' weights. I know all of them. I get a "packet" which I know is travelling from A to B currently on node C. How to get minimal path it can be presently traversing (next and previous nodes)?


Solution

  • The shortest path A -> C -> B must have the shortest A->C and C->B subpaths. It is trivial to prove. Note. The shortest path A -> B might not traverse C. Therefore the answer by @x00 might fail if you don't have apriory guarantee that C is selected correctly from the shortest path.

    The previous node is the last segment on the path A->C and the next node is the first segment of the path C->B.

    The shortest paths could be computed using Dijkstra algorithm.