python构建有向图_使用Python库生成有向图任何Python库

本文介绍了如何利用Python的`networkx`库创建有向图,并结合代码展示了在实现Bellman-Ford算法过程中如何以图形方式表示节点、边及其权重。此外,还提供了含有负权重边的图示例。
摘要由CSDN通过智能技术生成

我正在用Python实现GeeksForGeeks的Bellman-ford算法。我想用pyplot或networkx之类的库生成图形(图解形式,而不是字典类型,这很容易)。我希望图形用户界面包含节点、边和各自的成本。在from collections import defaultdict

#Class to represent a graph

class Graph:

def __init__(self,vertices):

self.V= vertices #No. of vertices

self.graph = [] # default dictionary to store graph

# function to add an edge to graph

def addEdge(self,u,v,w):

self.graph.append([u, v, w])

# utility function used to print the solution

def printArr(self, dist):

print("Vertex Distance from Source")

for i in range(self.V):

print("%d \t\t %d" % (i, dist[i]))

# The main function that finds shortest distances from src to

# all other vertices using Bellman-Ford algorithm. The function

# also detects negative weight cycle

def BellmanFord(self, src):

# Step 1: Initi

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值