📅  最后修改于: 2023-12-03 15:08:03.423000             🧑  作者: Mango
在有向图中,我们可以通过DFS和BFS找到负权重循环。本文将介绍如何通过BFS算法在有向图中打印负权重循环。
from collections import deque
def print_negative_weight_cycle(graph, n):
distance = [float('inf')] * n # 初始距离为无穷
distance[0] = 0 # 起始顶点距离为0
queue = deque()
queue.append(0)
parent = [-1] * n # 记录每个顶点的父节点
cycle_start = -1 # 记录负权重循环的起点
cycle_end = -1 # 记录负权重循环的终点
while queue:
current = queue.popleft()
for neighbor, weight in graph[current]:
if distance[neighbor] == float('inf'):
distance[neighbor] = distance[current] + weight
parent[neighbor] = current
queue.append(neighbor)
elif distance[neighbor] + weight < distance[current]:
cycle_start, cycle_end = neighbor, current
break
if cycle_start != -1:
break
if cycle_start == -1:
print("No negative weight cycle found.")
else:
print("Negative weight cycle found:")
cycle = [cycle_start]
while cycle_end != cycle_start:
cycle.append(cycle_end)
cycle_end = parent[cycle_end]
cycle.append(cycle_start)
print(cycle[::-1])
该算法的时间复杂度为O(mn),其中m和n分别为有向图中边的数量和顶点的数量。
本文介绍了如何通过BFS算法在有向图中打印负权重循环。需要注意的是,该算法只能检测到存在负权重循环,但不能检测到不存在负权重循环的情况。因此,在实际使用中需要对算法进行适当的改进。