All paths of length L from node n using python

前端 未结 5 1437
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 07:34

Given a graph G, a node n and a length L, I\'d like to collect all (non-cyclic) paths of length L that depart from n.

Do you have any idea on how to approach this?

5条回答
  •  没有蜡笔的小新
    2020-12-16 08:36

    Here is another (rather naive) implementation I came up with after reading the answers here:

    def findAllPaths(node, childrenFn, depth, _depth=0, _parents={}):
        if _depth == depth - 1:
            # path found with desired length, create path and stop traversing
            path = []
            parent = node
            for i in xrange(depth):
                path.insert(0, parent)
                if not parent in _parents:
                    continue
                parent = _parents[parent]
                if parent in path:
                    return # this path is cyclic, forget
            yield path
            return
    
        for nb in childrenFn(node):
            _parents[nb] = node # keep track of where we came from
            for p in findAllPaths(nb, childrenFn, depth, _depth + 1, _parents):
                yield p
    
    
    graph = {
        0: [1, 2],
        1: [4, 5],
        2: [3, 10],
        3: [8, 9],
        4: [6],
        5: [6],
        6: [7],
        7: [],
        8: [],
        9: [],
        10: [2] # cycle
    }
    
    for p in findAllPaths(0, lambda n: graph[n], depth=4):
        print(p)
    
    # [0, 1, 4, 6]
    # [0, 1, 5, 6]
    # [0, 2, 3, 8]
    # [0, 2, 3, 9]
    

提交回复
热议问题