当前位置:文档之家› 源代码--数据结构与算法(Python版)第8章 图

源代码--数据结构与算法(Python版)第8章 图

目录第8章图 (2)图的邻接矩阵举例 (2)图的邻接表举例 (5)8.3 图的遍历 (6)8.3.1 深度优先遍历 (7)8.3.2 广度优先遍历 (8)8.4 最小生成树 (9)8.4.1 克鲁斯卡尔(Kruskal)算法 (9)8.4.2 普里姆(Prim)算法 (12)8.5 最短路径 (14)14168.617 (17)18第8章图图的邻接矩阵举例import networkx as nx #调用networkximport matplotlib.pyplot as plt #调用matplotlib,绘制图class Graph_Matrix: #邻接矩阵Adjacency Matrixdef __init__(self, vertices=[], matrix=[]):self.matrix = matrixself.edges_dict = {} # {(tail, head):weight}self.edges_array = [] # (tail, head, weight)self.vertices = verticesself.num_edges = 0if len(matrix) > 0: #创建边的列表if len(vertices) != len(matrix):raise IndexErrorself.edges = self.getAllEdges()self.num_edges = len(self.edges)elif len(vertices) > 0: #节点列表self.matrix = [[0 for col in range(len(vertices))] for row in range(len(vertices))] self.num_vertices = len(self.matrix)def isOutRange(self, x): #越界try:if x >= self.num_vertices or x <= 0:raise IndexErrorexcept IndexError:print("节点下标出界")def isEmpty(self): #是否为空if self.num_vertices == 0:self.num_vertices = len(self.matrix)return self.num_vertices == 0def add_vertex(self, key): #添加结点if key not in self.vertices:self.vertices[key] = len(self.vertices) + 1# 添加一个节点意味着添加行和列, 对每一行都添加一列for i in range(self.getVerticesNumbers()):self.matrix[i].append(0)self.num_vertices += 1nRow = [0] * self.num_verticesself.matrix.append(nRow)def getVertex(self, key): #返回节点passdef add_edges_from_list(self, edges_list): # 边列表: [(tail, head, weight),()]for i in range(len(edges_list)):self.add_edge(edges_list[i][0], edges_list[i][1], edges_list[i][2], )def add_edge(self, tail, head, cost=0): #添加边if tail not in self.vertices:self.add_vertex(tail)if head not in self.vertices:self.add_vertex(head)self.matrix[self.vertices.index(tail)][self.vertices.index(head)] = costself.edges_dict[(tail, head)] = costself.edges_array.append((tail, head, cost))self.num_edges = len(self.edges_dict)def getEdges(self, V): # 返回边passdef getVerticesNumbers(self): #返回节点数目if self.num_vertices == 0:self.num_vertices = len(self.matrix)return self.num_verticesdef getAllVertices(self): #返回所有的节点return self.verticesdef getAllEdges(self): #返回所有的边for i in range(len(self.matrix)):for j in range(len(self.matrix)):if 0 < self.matrix[i][j] < float('inf'):self.edges_dict[self.vertices[i], self.vertices[j]] = self.matrix[i][j]self.edges_array.append([self.vertices[i], self.vertices[j], self.matrix[i][j]]) return self.edges_arraydef __repr__(self):return str(''.join(str(i) for i in self.matrix))def to_do_vertex(self, i):print('vertex: %s' % (self.vertices[i]))def to_do_edge(self, w, k):print('edge tail: %s, edge head: %s, weight: %s' % (self.vertices[w], self.vertices[k], str(self.matrix[w][k])))def create_undirected_matrix(my_graph):nodes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']matrix = [[0, 1, 1, 1, 1, 1, 0, 0], # a[0, 0, 1, 0, 1, 0, 0, 0], # b[0, 0, 0, 1, 0, 0, 0, 0], # c[0, 0, 0, 0, 1, 0, 0, 0], # d[0, 0, 0, 0, 0, 1, 0, 0], # e[0, 0, 1, 0, 0, 0, 1, 1], # f[0, 0, 0, 0, 0, 1, 0, 1], # g[0, 0, 0, 0, 0, 1, 1, 0]] # hmy_graph = Graph_Matrix(nodes, matrix)print(my_graph)return my_graphdef draw_undircted_graph(my_graph):G = nx.Graph() # 建立一个空的无向图Gfor node in my_graph.vertices: #添加节点G.add_node(str(node))for edge in my_graph.edges: #添加边G.add_edge(str(edge[0]), str(edge[1]))print("nodes:", G.nodes()) # 输出全部的节点print("edges:", G.edges()) # 输出全部的边print("number of edges:", G.number_of_edges()) # 输出边的数量nx.draw(G, with_labels=True)plt.savefig("undirected_graph.png")plt.show()if __name__=='__main__':my_graph = Graph_Matrix()create_graph=create_undirected_matrix(my_graph)draw_undircted_graph(create_graph)【程序运行结果如下所示】[0, 1, 1, 1, 1, 1, 0, 0][0, 0, 1, 0, 1, 0, 0, 0][0, 0, 0, 1, 0, 0, 0, 0][0, 0, 0, 0, 1, 0, 0, 0][0, 0, 0, 0, 0, 1, 0, 0][0, 0, 1, 0, 0, 0, 1, 1][0, 0, 0, 0, 0, 1, 0, 1][0, 0, 0, 0, 0, 1, 1, 0]nodes: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']edges: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('a', 'f'), ('b', 'c'), ('b', 'e'), ('c', 'd'), ('c', 'f'), ('d', 'e'), ('e', 'f'), ('f', 'g'), ('f', 'h'), ('g', 'h')]number of edges: 14程序运行如图8.5所示。

相关主题