查找图实现中的所有循环

Kal*_*ali 2 python algorithm graph directed-graph

我发现了一个简单的算法来找到一个图所有循环这里。我也需要打印出周期,这个算法可以吗?请在下面找到代码。

我得到正确的周期数!

node1, node2 是整数。访问的是一本字典

def dfs(self,node1, node2):
    if self.visited[node2]:
        if(node1 == node2):
            self.count += 1
            print node2
        return

    self.visited[node2] = True

    for x in self.adj_lst[node2-1]:
        self.dfs(node1, x)

    self.visited[node2] = False

def allCycles(self):
    self.count = 0
    for x in self.VList:
        self.dfs(x.num, x.num)
        self.visited[x.num] = True

    print "Number of cycles: "+str(self.count)
Run Code Online (Sandbox Code Playgroud)

ACh*_*ion 8

是的,您当然可以构建路径,现在您可以递归地进行构建,但我不太喜欢在类中管理临时状态。

这是使用 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]]
Run Code Online (Sandbox Code Playgroud)

注意: 4 不能回到自身。