# 贪心算法之Bellman-Ford

``# This Python file uses the following encoding: utf-8 import sys lineNum=0 nodeNum=0 dist = [] pre = [] sourceNode = -1 dataFile = open('e:\\drg.data', 'r') [ nodeNum, sourceNode ] = dataFile.readline().split("\t") dataFile.close() print (nodeNum, sourceNode) nodeNum = int(nodeNum) sourceNode = int(sourceNode) - 1 dist = [10000 for i in range(nodeNum)] pre = [-1 for i in range(nodeNum)] dist[sourceNode] = 0 dataFile = open('e:\\drg.data', 'r') dataFile.readline() for line in dataFile.readlines(): #其实就是Dijkstra算法中的对边进行松弛 [frm, to, wei] = line.split("\t") frm = int(frm)-1 to = int(to)-1 wei = int(wei) if (dist[frm] + wei < dist[to]): dist[to] = dist[frm] + wei pre[to] = frm dataFile.close() for i in range(len(dist)): print (i, dist[i]) dataFile = open('e:\\drg.data', 'r') dataFile.readline() for line in dataFile.readlines(): #对负权环进行检测 [frm, to, wei] = line.split("\t") frm = int(frm)-1 to = int(to)-1 wei = int(wei) if (dist[frm] + wei < dist[to]): print ("Graph contains a neg-wei cycle") dataFile.close()``

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/csy463168656/article/details/8128377
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。