本文为左神《算法入门与基础提升》课中“第六节 图结构”的总结
左神用java实现的
本人比较熟悉python
用python写了一遍
#节点的类
class Node:
def __init__(self,value=0,n_in=0,n_out=0,nextlist=[],edgelist=[]):
self.val = value#该node的值
self.n_in = n_in#该node的入度,即有多少边连向这个node
self.n_out = n_out#该node的出度,即有多少边从这个node发散出去
self.next_list = nextlist#从该节点直接发散出去的边连接的点
self.edge_list = edgelist#与该节点连接的边
#边的类
class Edge:
def __init__(self,weight=0,from_which=0,to_which=0):
self.weight = weight#该edge的权值
self.from_which = from_which#该edge从哪里发出
self.to_which = to_which#该edge终止于哪个点
#图的类
class Graph:
def __init__(self,node_dict={},edge_set=set()):
self.node_dict = node_dict#{node_0.val:node_0,node_1.val:node_1,...,node_n.val:node_n}
self.edge_set = edge_set#{edge_0,edge_1,...,edge_m}
'''
假设用户给的图的表征方法是
[[weight,from,to]]
如何将这种二维数组转化到我们自己定义的图?
'''
class Graph_Generator:
def create_graph(self,edge_list):
newGraph = Graph({},set())#先定义一个空图
#一行一行遍历二维数组,取其中每一个成员一维数组的weight from to
for each_list in edge_list:
this_weight = each_list[0]
this_from = each_list[1]
this_to = each_list[2]
#注册点,考虑 如果this_from或this_to不存在于当前Graph实例的node_dict中
#则将其注册进去
if this_from not in newGraph.node_dict:
newGraph.node_dict[this_from] = Node(value = this_from)
if this_to not in newGraph.node_dict:
newGraph.node_dict[this_to] = Node(value = this_to)
#经过上述两种注册过程后
#确保有this_from和this_to点了
#先拿出这两个点
from_node = newGraph.node_dict[this_from]
to_node = newGraph.node_dict[this_to]
#在图中建立边
this_edge = Edge(this_weight,from_node,to_node)
#将to_node放到from_node的next_list中
#并将其n_out加1
from_node.next_list.append(to_node)
from_node.n_out += 1
#将to_node的n_in加1
to_node.n_in += 1
#将这条边加到from_node的edgelist中
from_node.edge_list.append(this_edge)
#将这条边加到图的
newGraph.edge_set.add(this_edge)
return newGraph
#此时可以执行测试代码1
#________________________________
#宽度优先遍历
class bfs_search:
def bfs(node):
if node == None:
return None
#使用队列,
#且用set去重,以保证不要让一个节点重复进入队列
this_queue = []
this_set = set()
this_queue.append(node)
this_set.add(node)
while this_queue != []:
cur = this_queue.pop(0)
print(cur.val)
for sub_node in cur.next_list:
if sub_node not in this_set:
this_set.add(sub_node)
this_queue.append(sub_node)
测试代码1
#测试Graph_Generator
edge_input_example = [[7,0,1],
[3,1,2],
[5,0,2]]
generator = Graph_Generator()
new_graph = generator.create_graph(edge_input_example)