使用Python库生成有向图

3

我正在用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: Initialize distances from src to all other vertices 
        # as INFINITE 
        dist = [float("Inf")] * self.V 
        dist[src] = 0 


        # Step 2: Relax all edges |V| - 1 times. A simple shortest  
        # path from src to any other vertex can have at-most |V| - 1  
        # edges 
        for i in range(self.V - 1): 
            # Update dist value and parent index of the adjacent vertices of 
            # the picked vertex. Consider only those vertices which are still in 
            # queue 
            for u, v, w in self.graph: 
                if dist[u] != float("Inf") and dist[u] + w < dist[v]: 
                        dist[v] = dist[u] + w 

        # Step 3: check for negative-weight cycles.  The above step  
        # guarantees shortest distances if graph doesn't contain  
        # negative weight cycle.  If we get a shorter path, then there 
        # is a cycle. 

        for u, v, w in self.graph: 
                if dist[u] != float("Inf") and dist[u] + w < dist[v]: 
                        print "Graph contains negative weight cycle"
                        return

        # print all distance 
        self.printArr(dist) 

g = Graph(5) 
g.addEdge(0, 1, -1) 
g.addEdge(0, 2, 4) 
g.addEdge(1, 2, 3) 
g.addEdge(1, 3, 2) 
g.addEdge(1, 4, 2) 
g.addEdge(3, 2, 5) 
g.addEdge(3, 1, 1) 
g.addEdge(4, 3, -3) 

我需要的图表(基于上述代码)可以在终端或单独的文件中显示: enter image description here

1
您不一定需要重新发明轮子。似乎networkx非常适合这个应用场景。 - ImportanceOfBeingErnest
2个回答

5

ekiim的文档链接非常有用。下面是我编写用于绘制图表的代码:

import networkx as nx  
import matplotlib.pyplot as plt
G=nx.DiGraph()
G.add_node(0),G.add_node(1),G.add_node(2),G.add_node(3),G.add_node(4)
G.add_edge(0, 1),G.add_edge(1, 2),G.add_edge(0, 2),G.add_edge(1, 4),G.add_edge(1, 3),G.add_edge(3, 2),G.add_edge(3,1),G.add_edge(4,3)
nx.draw(G, with_labels=True, font_weight='bold')
plt.show()

这段代码可以打印不带成本的有向图。我尝试过带有成本的打印,但输出结果相当混乱,成本错乱,一些成本写在空白处,而只有一两个成本显示在边缘上。因此,如果有人知道如何实现带有成本的打印,那将非常有用。


2
如果您查看这个networkx的教程,您会发现创建有向图以及绘制它是非常容易的。对于有向图或简单图(API方面),几乎相同,而且绘图也足够简单,使用Matplotlib生成即可。
您可以制作一个Tk应用程序,手动输入节点和边缘,并将它们存储在ListBoxes中,在此基础上绘制图形,这不会是拖放,但仍然可以帮助您实时可视化图形。
这个Matplotlib的教程,将为您提供如何将其嵌入到TK应用程序中的想法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接