Find all cycles in a graph implementation

后端 未结 2 1522
离开以前
离开以前 2020-12-20 00:51

I have found a simple algorithm to find all cycles in a graph here. I need to print out the cycles too, is it possible with this algorithm. Please find the code below.

相关标签:
2条回答
  • 2020-12-20 01:03

    Yes, it's possible. You can just store the parent of each vertex and then iterate over the array of parents (until you reach the start vertex) to print the cycle when you find one.

    0 讨论(0)
  • 2020-12-20 01:13

    Yes of course you can construct the path, now you can do it recursively but I'm not a great fan of managing temporary state in the class.

    Here's a simple implementations using a stack:

    def dfs(graph, start, end):
        fringe = [(start, [])]
        while fringe:
            state, path = fringe.pop()
            if path and state == end:
                yield path
                continue
            for next_state in graph[state]:
                if next_state in path:
                    continue
                fringe.append((next_state, path+[next_state]))
    
    >>> graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }
    >>> cycles = [[node]+path  for node in graph for path in dfs(graph, node, node)]
    >>> len(cycles)
    7
    >>> cycles
    [[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]]
    

    Note: 4 cannot get back to itself.

    0 讨论(0)
提交回复
热议问题