繁体   English   中英

在有向图和无向图中查找所有循环

[英]Find all cycles in directed and undirected graph

我希望能够找到有向图和无向图的所有周期。

如果有向图中是否存在循环,则以下代码将返回True或False:

def cycle_exists(G):                     
    color = { u : "white" for u in G  }  
    found_cycle = [False]               

    for u in G:                          
        if color[u] == "white":
            dfs_visit(G, u, color, found_cycle)
        if found_cycle[0]:
            break
    return found_cycle[0]


def dfs_visit(G, u, color, found_cycle):
    if found_cycle[0]:                         
        return
    color[u] = "gray"                         
    for v in G[u]:                              
        if color[v] == "gray":                  
            found_cycle[0] = True       
            return
        if color[v] == "white":                    
            dfs_visit(G, v, color, found_cycle)
    color[u] = "black"

如果无向图中是否存在循环,则以下代码将返回True或False:

def cycle_exists(G):                                 
    marked = { u : False for u in G }    
    found_cycle = [False]                                                       

    for u in G:                          
        if not marked[u]:
            dfs_visit(G, u, found_cycle, u, marked)     
        if found_cycle[0]:
            break
    return found_cycle[0]

def dfs_visit(G, u, found_cycle, pred_node, marked):
    if found_cycle[0]:                             
        return
    marked[u] = True                                 
    for v in G[u]:                                    
        if marked[v] and v != pred_node:             
            found_cycle[0] = True                     
            return
        if not marked[v]:                            
            dfs_visit(G, v, found_cycle, u, marked)

graph_example = { 0 : [1],
                  1 : [0, 2, 3, 5],  
                  2 : [1],
                  3 : [1, 4],
                  4 : [3, 5],
                  5 : [1, 4] }

如何使用这些来查找有向图和无向图中存在的所有循环?

据我了解,您的问题是对有向图和无向图使用一种独特的算法。

为什么不能使用该算法检查无向图上的有向环? 无向图是有向图的一种特殊情况 您可以认为一个无向边是由一个向前和向后的有向边构成的。

但是,这不是很有效。 通常,您的问题陈述将指示图形是否是有向的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM