实施DFS以在无向图中查找循环,并通过递归查找每个循环的节点数

时间:2019-06-26 20:34:16

标签: python python-3.x recursion graph

我是图形算法和递归的初学者。我试图找到一种递归的方法来检测图中的周期以及每个周期的节点数。

但是,似乎我没有成功获得解决方案,并且即使在使用谷歌搜索之后也找不到对我的问题的递归答案(我发现的全部都是迭代解决方案)。

CYCLE, PATH = 0,1

def main():
    global adjlist, visited
    n, m = map(int, input().split())
    adjlist = [[0 for i in range(n)] for j in range(n)]
    visited = [0 for i in range(n)]
    for i in range(m):
        a ,b = map(int, input().split())
        a, b = a-1, b-1
        adjlist[a][b] = 1
        adjlist[b][a] = 1

    for i in range(n):
        if not visited[i]:
            nodeCount, status = dfs(i)
            print("i:",i+1,"node count:", nodeCount,"status:", "path" if status == PATH else "cycle")


def dfs(currentNode, parentNode = -1, nodeCount=0):
    if visited[currentNode]:
        return nodeCount, CYCLE
    visited[currentNode] = 1
    for neighbor in adjlist[currentNode]:
        if not visited[neighbor] and neighbor != parentNode:
            newNodeCount, status = dfs(neighbor, currentNode, nodeCount)
            nodeCount += newNodeCount
            if status == CYCLE:
                return CYCLE, nodeCount

    return PATH, nodeCount

main()

这是我提供此输入时得到的

5 4
1 2
2 3
1 3
4 5

i: 1 node count: 0 status: path
i: 3 node count: 1 status: cycle
i: 4 node count: 1 status: cycle
i: 5 node count: 1 status: cycle

0 个答案:

没有答案