Search for all possible paths in a graph

I'm looking for some algorithm which will help me find all possible ways in the graph. Everything that I have found so far is not completely satisfactory.

Suppose we have a graph (tree) like this:
enter image description here

And let me use some algorithm, such as Width and First Search or Depth Search . In return, we get something like

1, 2, 4, (2), 5, (2), 6, (2), (1), 3, 7, 8, (7), 9

This is how we go through this tree, and this is not what I am looking for. I would like to get all the paths, for example:

1
1, 2
1, 2, 4
1, 2, 5
1, 2, 6
1, 3
1, 3, 7
1, 3, 7, 8
1, 3, 7, 9

The thing is, I just want to specify rootnode, and the algorithm should be able to provide me with all possible paths of any length.


So far, the simple code I had looks like this:

func dfs(_ graph: Graph, source: Node) -> [String] {
    var nodesExplored = [source.label]
    source.visited = true

    for edge in source.neighbors {
        if !edge.neighbor.visited {
            nodesExplored += dfs(graph, source: edge.neighbor)
        }
    }

    return nodesExplored
}
+3
2

, root-to-leaf. treePaths - (DFS), , .

treePaths(root, path[1000], 0) // initial call, 1000 is a path length limit

// treePaths traverses nodes of tree DFS, pre-order, recursively
treePaths(node, path[], pathLen)
    1) If node is not NULL then 
        a) push data to path array: 
            path[pathLen] = node->data.
        b) increment pathLen 
            pathLen++
    2) If node is a leaf node, then print the path array, from 0 to pathLen-1
    3) Else
        a) Call treePaths for left subtree
            treePaths(node->left, path, pathLen)
        b) Call treePaths for right subtree.
            treePaths(node->right, path, pathLen)
0

: = 9 ( [1])

n0  n1  n2  n3
1,   2,  4,       +3
    (2), 5,       +1
    (2), 6,       +1
    (2),          +0
(1), 3,  7,  8,   +3
        (7), 9    +1
0

Source: https://habr.com/ru/post/1682472/


All Articles