Efficient algorithm to find all the paths from A to Z?

前端 未结 4 1305
失恋的感觉
失恋的感觉 2020-12-23 15:01

With a set of random inputs like this (20k lines):

A B
U Z
B A
A C
Z A
K Z
A Q
D A
U K
P U
U P
B Y
Y R
Y U
C R
R Q
A D
Q Z

Find all the pat

4条回答
  •  再見小時候
    2020-12-23 15:45

    What you're proposing is a scheme for DFS, only with backtracking.It's correct, unless you want to permit cyclic paths (you didn't specify if you do).

    There are two gotchas, though.

    1. You have to keep an eye on nodes you already visited on current path (to eliminate cycles)
    2. You have to know how to select next node when backtracking, so that you don't descend on the same subtree in the graph when you already visited it on the current path.

    The pseudocode is more or less as follows:

    getPaths(A, current_path) :
        if (A is destination node): return [current_path]
        for B = next-not-visited-neighbor(A) : 
            if (not B already on current path) 
                result = result + getPaths(B, current_path + B)
        return result 
    
     list_of_paths =  getPaths(A, [A])
    

    which is almost what you said.

    Be careful though, as finding all paths in complete graph is pretty time and memory consuming.

    edit For clarification, the algorithm has Ω(n!) time complexity in worst case, as it has to list all paths from one vertex to another in complete graph of size n, and there are at least (n-2)! paths of form . No way to make it better if only listing the result would take as much.

提交回复
热议问题