【发布时间】:2020-06-17 01:11:17
【问题描述】:
我正在尝试在 python 中编写一个程序,该程序计算使用邻接列表(python 中的dict())表示的图中的循环数(连接的组件)。
基本上,我运行 DFS 并检查是否已经访问了相邻顶点,并且该顶点不是当前顶点的父顶点。如果是这种情况,则图中存在一个循环。然后我计算这种情况发生的次数。
def count_cycles(graph, start, visited, count=0):
visited[start] = True
for next in graph[start]:
if not visited[next]:
count_cycles(graph, next, visited, count)
elif start != next:
count += 1
return count
if __name__ == "__main__":
graph = {
3: {10},
4: {8},
6: {3},
7: {4, 6},
8: {7},
10: {6}
}
visited = [False] * (max(graph)+1)
print(count_cycles(graph, 8, visited))
在示例中,输出应该是 2,但它会打印 1。我怀疑我的 DFS 存在问题,但我无法准确地弄清楚。
有什么建议吗?
【问题讨论】:
-
当我运行你的代码时,我得到的输出是 0?您是否提交了正确的代码?
-
如果我要猜测该怎么做,我会尝试将 count=0 放在函数自身行的第一行,而不是将其作为变量传递。
标签: python graph-theory depth-first-search connected-components