Python算法教程:强连通分量
生活随笔
收集整理的這篇文章主要介紹了
Python算法教程:强连通分量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
強連通分量(strongly connected components, SCCs)是一個能讓有向路徑上所有節點彼此到達的最大子圖。
Kosaraju的查找強連通分量算法
def strongly_connected_components(graph):transpose_graph = get_transpose_graph(graph)scc, seen = [], set()for u in dfs_top_sort(graph):if u in seen:continuecomponent = walk(transpose_graph, u, seen)seen.update(component)scc.append(component)return sccdef get_transpose_graph(graph):transposed = {}for u in graph:transposed[u] = set()for u in graph:for v in graph[u]:transposed[v].add(u)return transposeddef dfs_top_sort(graph):visited, res = set(), []def recurse(u):if u in visited:returnvisited.add(u)for v in graph[u]:recurse(v)res.append(u)for u in graph:recurse(u)res.reverse()return resdef walk(graph, start, s=None):nodes, current = set(), dict()current[start] = Nonenodes.add(start)while nodes:u = nodes.pop()for v in graph[u].difference(current, s):nodes.add(v)current[v] = ureturn currentgraph = {'a': set('bc'),'b': set('dei'),'c': set('d'),'d': set('ah'),'e': set('f'),'f': set('g'),'g': set('eh'),'h': set('i'),'i': set('h'), } print(strongly_connected_components(graph)) # [{'a': None, 'd': 'a', 'b': 'd', 'c': 'd'}, {'e': None, 'g': 'e', 'f': 'g'}, {'h': None, 'i': 'h'}](最近更新:2019年05月31日)
總結
以上是生活随笔為你收集整理的Python算法教程:强连通分量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬虫实现网页采集器
- 下一篇: C语言扫雷游戏简单实现