数据结构
class Node:
def __init__(self, value):
self.value = value
self.in_num = 0
self.out_num = 0
self.nexts = []
self.edges = []
class Edge:
def __init__(self, weight, n_from, n_to):
self.weight = weight
self.n_from = n_from
self.n_to = n_to
class Graph:
def __init__(self):
self.nodes = {}
self.edges = []
class GraphGenerator:
"""
这相当于一个接口函数,将各种条件统一转化为上面的图的结构,根据具体情况改写此类即可。
"""
def createGraph(self, matrix):
graph = Graph()
for i in range(len(matrix)):
weight = matrix[i][0]
n_from = matrix[i][1]
n_to = matrix[i][2]
if n_from not in graph.nodes.keys():
graph.nodes[n_from] = Node(n_from)
if n_to not in graph.nodes.keys():
graph.nodes[n_to] = Node(n_to)
fromNode = graph.nodes[n_from]
toNode = graph.nodes[n_to]
edge = Edge(weight, fromNode, toNode)
fromNode.nexts.append(toNode)
fromNode.out_num += 1
toNode.in_num += 1
fromNode.edges.append(edge)
graph.edges.append(edge)
return graph
m = [[5, 0, 7], [3, 0, 1]]
g = GraphGenerator()
graph = g.createGraph(m)
print(str(graph.nodes.keys()))
for i in range(len(graph.edges)):
print(str([graph.edges[i].weight, graph.edges[i].n_from.value, graph.edges[i].n_to.value]))
宽度优先算法
class BFS:
def bfs(self, start):
if start is None: return
que = [start]
set = [start]
while len(que) >0:
cur = que.pop(0)
print(cur.value)
for next in cur.nexts:
if next not in set:
set.append(next)
que.append(next)
m = [[3, 0, 1],
[2, 0, 2],
[4, 1, 2],
[2, 1, 3]]
gen = GraphGenerator()
graph = gen.createGraph(m)
search = BFS()
print("从0开始,宽度优先搜索:")
search.bfs(graph.nodes[0])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!