欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

python实现图的结构

时间:2023-08-22
节点定义

# 图节点结构class Node:def __init__(self, value):self.value = value # 节点值self.come = 0 # 入度self.out = 0 # 出度self.nexts = [] # 邻居节点self.edges = [] # 在节点为from的情况下,边的集合

边定义

class Edges:def __init__(self, weight, from, to):self.weight = weight # 边的权重 self.fro = fro # 边的from节点 self.to = to # 边的to节点

图结构

class Graph:def __init__(self):self.nodes = {} # 图的所有节点集合 字典形式:{节点编号:节点}self.edges = [] # 图的边集合

图的实现

# 生成图结构# matrix = [# [1,2,3], ==> 里面分别代表权重, from节点, to节点# [...]# ]from Graph import Graphfrom Node import Nodefrom Edge import Edgedef createGraph(matrix): graph = Graph() for edge in matrix: weight = edge[0] fro = edge[1] to = edge[2] if fro not in graph.nodes: graph.nodes[fro] = Node(fro) if to not in graph.nodes: graph.nodes[to] = Node(to) fromNode = graph.nodes[fro] tonode = graph.nodes[to] newEdge = Edge(weight, fromNode, toNode) fromNode.nexts.append(toNode) fromNode.out += 1 toNode.come += 1 fromNode.edges.append(newEdge) graph.edges.append(newEdge) return graph

原文:
https://www.cnblogs.com/icekx/p/915244a4.html

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。