0
我希望能够在有向图和无向图中查找所有循环。查找有向图和无向图中的所有循环
在下面的代码,如果一个周期中的有向图的存在与否返回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] }
如何使用这些查找定向和无向图中存在的所有循环?