python实现图的结构
2022/2/5 11:12:41
本文主要是介绍python实现图的结构,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
节点定义
# 图节点结构 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 Graph from Node import Node from Edge import Edge def 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
这篇关于python实现图的结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型