图的宽度遍历python实现

#File Name : 图 宽度遍历.py
from queue import  Queue
class Node(object):
    def __init__(self,value=None):
        self.value = value #节点的值
        self.come = 0 #节点入度
        self.out = 0 #节点出度
        self.nexts = [] #节点的邻居节点
        self.edges = [] #在节点为from的情况下,边的集合
class Edge(object):
    def __init__(self,weight=None,fro,to):
        self.weight = weight # 边的权重
        self.fro = fro # 边的from节点
        self.to = to #边的to节点
class Graph(object):
    def __init__(self):
        self.nodes = {} #图所有节点的集合  字典形式 :{节点编号:节点}
        self.edges = [] #图的边集合

def creatGraph(matrix):
    # 二维数组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 #出度+1
        toNode.come+=1 #to 的入度+1
        fromNode.edge.append(newEdge) #边的集合+1
        graph.edges.append(newEdge)

    return graph

def bfs(node):
    if node is None:
        return
    # 建立一个栈
    queue = Queue()
    # 建立一个集合
    nodeset = set()
    # 队列用于弹出和存取
    queue.put(node)
    # 集合用于检查是否有重复
    nodeset.add(node)
    while not queue.empty():
        cur = queue.get() #弹出元素
        print(cur.value)
        for next in cur.nexts:
            if next not in nodeset:
                nodeset.add(next)
                queue.put(next)

# Queue 模块
#Queue.put(item) 写入队列
#Queue.empty() 若为空 返回True
#Queue.get() 弹出元素

# 建立空集合必须用 set() 不能{} 因为他是空字典
# set.add()
# 集合没有顺序的概念

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值