图的结构 Python实现
1.每个节点类型设置
1 # 图的节点结构 2 class Node: 3 def __init__(self, value): 4 self.value = value # 节点值 5 self.come = 0 # 节点入度 6 self.out = 0 # 节点出度 7 self.nexts = [] # 节点的邻居节点 8 self.edges = [] # 在节点为from的情况下,边的集合
2.每条边类型设置
1 # 图的边结构 2 class Edge: 3 def __init__(self, weight, fro, to): 4 self.weight = weight # 边的权重 5 self.fro = fro # 边的from节点 6 self.to = to # 边的to节点
3.图的结构
1 # 图结构 2 class Graph: 3 def __init__(self): 4 self.nodes = {} # 图的所有节点集合 字典形式:{节点编号:节点} 5 self.edges = [] # 图的边集合
4.图的实现
1 # 生成图结构 2 # matrix = [ 3 # [1,2,3], ==> 里面分别代表权重, from节点, to节点 4 # [...] 5 # ] 6 from Graph import Graph 7 from Node import Node 8 from Edge import Edge 9 10 11 def createGraph(matrix): 12 graph = Graph() 13 for edge in matrix: 14 weight = edge[0] 15 fro = edge[1] 16 to = edge[2] 17 if fro not in graph.nodes: 18 graph.nodes[fro] = Node(fro) 19 if to not in graph.nodes: 20 graph.nodes[to] = Node(to) 21 fromNode = graph.nodes[fro] 22 toNode = graph.nodes[to] 23 newEdge = Edge(weight, fromNode, toNode) 24 fromNode.nexts.append(toNode) 25 fromNode.out += 1 26 toNode.come += 1 27 fromNode.edges.append(newEdge) 28 graph.edges.append(newEdge) 29 return graph
Talk is cheap, show my code to you.