用python 写一个 判断 无向图里有没有环的示例
时间: 2023-03-08 16:55:46 浏览: 127
python判断无向图环是否存在的示例
我可以给你一个用python写的判断无向图里有没有环的示例:# 定义无向图
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}# 定义深度优先搜索函数
def dfs(graph, node, visited):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph,n, visited)
return visited# 检查是否存在环
def has_cycle(graph):
visited = []
# 从每个节点开始搜索
for node in graph:
visited = dfs(graph, node, visited)
# 如果搜索的节点数与图中节点数相同,说明存在环
if len(visited) == len(graph):
return True
visited = []
return False# 调用函数
if has_cycle(graph):
print('Graph has a cycle.')
else:
print('Graph does not have a cycle.')
阅读全文