栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实现图的结构

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/725724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号