#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()
# 集合没有顺序的概念