【问题标题】:Python: Counting number of connected components in adj. list representation of graphPython:计算 adj 中连接组件的数量。图的列表表示
【发布时间】: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


【解决方案1】:

知道了,您需要通过递归调用更新计数。

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 2020-02-19
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2020-08-17
    相关资源
    最近更新 更多