def traversal(g: Graph, end) -> list: res = [] vertex = g.get_vertex(end) while vertex: res.append(vertex.id) vertex = vertex.predecessor return res
def bfs(g: Graph, start, end) -> int: start_vertex = g.get_vertex(start) end_vertex = g.get_vertex(end) if start_vertex is None or end_vertex is None: raise ValueError(f'{start}或{end}不在单词表中') queue, found = Queue(), False queue.enqueue(start_vertex) while not queue.is_empty() and not found: vertex: Vertex = queue.dequeue() for neighbor in vertex.connect: if neighbor.color == 'white': neighbor.color = 'gray' neighbor.predecessor = vertex neighbor.distance = vertex.distance + vertex.get_weight( neighbor) queue.enqueue(neighbor) # 找到目标时提前退出 # if neighbor is end_vertex: # found = True vertex.color = 'black' return end_vertex.distance
def prim(g: Graph): # 随机选择一个起始顶点 start_vertex = g.get_vertex(choice(g.get_all_vertex())) # 初始化 init_graph(g) start_vertex.distance = 0 queue = PriorityQueue() vertex_list = [(vertex, vertex.distance) for vertex in g] queue.build_queue(vertex_list) while not queue.is_empty(): vertex: Vertex = queue.dequeue() for neighbor in vertex.connect: if neighbor not in queue: continue new_cost = vertex.get_weight(neighbor) if new_cost < neighbor.distance: neighbor.distance = new_cost neighbor.predecessor = vertex queue.update_priority(neighbor, new_cost)
def dijkstra(g: Graph, start) -> Vertex: start_vertex = g.get_vertex(start) if start_vertex is None: raise ValueError(f'{start}点不存在') # 初始化 init_graph(g) start_vertex.distance = 0 queue = PriorityQueue() vertex_list = [(vertex, vertex.distance) for vertex in g] queue.build_queue(vertex_list) while not queue.is_empty(): vertex: Vertex = queue.dequeue() for neighbor in vertex.connect: new_distance = vertex.distance + vertex.get_weight(neighbor) if new_distance < neighbor.distance: neighbor.distance = new_distance neighbor.predecessor = vertex queue.update_priority(neighbor, new_distance) return start_vertex
g.add_edge('a', 'c', 3) g.add_edge('c', 'f', 5) g.add_edge('f', 'g', 1) g.add_edge('b', 'e', 4) g.add_edge('b', 'd', 1) g.add_edge('b', 'c', 1) g.add_edge('d', 'e', 1) print 'Graph data:' for v in g: for w in v.get_connections(): vid = v.get_id() wid = w.get_id() print '( %s , %s, %3d)' % (vid, wid, v.get_weight(w)) prims(g, g.get_vertex('a')) ### floyd warshall algorithm for all vertex shortest path from pythonds.graphs import Graph, Vertex def floyd_Warshall(aGraph): distmat = [[100 for x in range(0, aGraph.numVertices + 1)] for y in range(0, aGraph.numVertices + 1)] for row in distmat: print row for num in range(0, aGraph.numVertices + 1): distmat[num][num] = 0