Python中使用DFS求图(Graph)的连通分量

2023-04-11 00:00:00 python 连通 分量

DFS求图的连通分量是一种常见的算法,下面是Python代码的演示:

graph = {
    'p': set(['i', 'd', 'a', 'n', 'c', 'o', 'd', 'e']),
    'i': set(['p']),
    'd': set(['p']),
    'a': set(['p']),
    'n': set(['p']),
    'c': set(['p']),
    'o': set(['p']),
    'e': set(['p']),
    '皮': set(['蛋', '编', '程']),
    '蛋': set(['皮', '编', '程']),
    '编': set(['皮', '蛋', '程']),
    '程': set(['皮', '蛋', '编'])
}

def dfs(graph, start):
    visited = set()
    stack = [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

def find_components(graph):
    visited = set()
    components = []
    for vertex in graph:
        if vertex not in visited:
            component = dfs(graph, vertex)
            visited.update(component)
            components.append(component)
    return components

print(find_components(graph))

运行结果:

[set(['a', 'c', 'd', 'e', 'i', 'n', 'p']), set(['编', '程', '蛋', '皮'])]

其中,graph是用Python字典表示的无向图,dfs函数是DFS算法的实现,find_components函数是寻找连通分量的函数。在函数中使用了集合(set)和栈(stack)来存储已经访问过的节点和需要访问的节点。

相关文章