Search code examples
algorithmmathematical-optimizationgraph-algorithm

All possible paths algorithm


I'm not very comfortable with math algorithms, and would need to use one for a project I'm working on. I have found answers for point A to point B, but none that really match what I'm looking for. I am looking for the best time efficient algorithm to accomplish this task:

For an input :

Points {
    In
    Out
}

[Bridge]Points = {
    "AB-1" = {"A", "B"}
    "AB-2" = {"A", "B"}
    "BA-1" = {"B", "A"}
    "BA-2" = {"B", "A"}
    "AC-1" = {"A", "C"}
    "AC-2" = {"A", "C"}
    "CA-1" = {"C", "A"}
    "CA-2" = {"C", "A"}
    "BC-1" = {"B", "C"}
    "BC-2" = {"B", "C"}
    "CB-1" = {"C", "B"}
    "CB-2" = {"C", "B"}
}

Each "bridge" represent 2 "points" : First value is an "in" and the second in an "out".

Each path can use each unique bridge only once. Different bridges can have the same in/out (like "BC-1","BC-2", ..), and each unique bridge must have a different in and out ("AA-1" = {"A", "A"} is not possible).

The goal is to obtain EVERY POSSIBLE paths given a start point and an end point, which can be the same points (A->A, B->B, ..).

For A to A expected output :

AB-1 -> BA-1
AB-1 -> BA-2
AB-2 -> BA-1
AC-1 -> CA-2
AB-1 -> BA-1 -> AB-2 -> BA-2
AB-1 -> BA-2 -> AC-1 -> CB-2 -> BA-1
AC-2 -> CA-1 -> AB-1 -> BA-2
AC-1 -> CA-1 -> AB-2 -> BC-1 -> CA-2
...

Also, the possibility of defining a maximum path length (to avoid subsequent processing within the algorithm) would be optional but very interesting. Thanking you for your time, I would very much appreciate your advice.


Solution

  • One could use a recursion like this (pseudo code):

    findPath(from, to, path_to_from) {
      if from == to { output path_to_from }
      for all bridges going out from 'from' that were not already used in path_to_from {
        findPath(bridge.out, to, path_to_from + bridge)
      }
    }
    

    and call it with findPath(A, B, empty_path) to output all paths from A to B.