Python:计算adj中连接组件的数量。图的列表表示
我正试图用python编写一个程序,用邻接列表(python中的dict()表示)计算图形中的循环数(连接的组件) 基本上,我运行DFS并检查是否已经访问了相邻顶点,并且该顶点不是当前顶点的父顶点。如果是这样的话,那么图中存在一个循环。然后我计算这种情况发生的次数Python:计算adj中连接组件的数量。图的列表表示,python,graph-theory,depth-first-search,connected-components,Python,Graph Theory,Depth First Search,Connected Components,我正试图用python编写一个程序,用邻接列表(python中的dict()表示)计算图形中的循环数(连接的组件) 基本上,我运行DFS并检查是否已经访问了相邻顶点,并且该顶点不是当前顶点的父顶点。如果是这样的话,那么图中存在一个循环。然后我计算这种情况发生的次数 def count_cycles(graph, start, visited, count=0): visited[start] = True for next in graph[start]: if
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有问题,但我无法准确地找出它
有什么建议吗?明白了,您需要通过递归调用更新计数
def count_cycles(graph, start, visited):
visited[start] = True
count = 0
for next in graph[start]:
if not visited[next]:
count += count_cycles(graph, next, visited)
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))
当我运行你的代码时,我得到的输出是0?您提交了正确的代码吗?如果我想猜怎么办,我会尝试将count=0放在函数自身行的第一行,而不是将其作为变量传递。