def topo_sort_dfs(g:Graph): #找出有入度的节点 in_nodes = set() for v in g: for nbr in v.getConnections(): in_nodes.add(nbr.id) #找出起始节点 start_nodes = [] for node in g.getVertices(): if node not in list(in_nodes): start_nodes.append(node) ''' 对递归版dfs做点改变 ''' def dfs(node:Vertex,path=''): if not node.getConnections(): paths.append(path + node.id) return for nbr in node.getConnections(): dfs(nbr,path + node.id) return paths = [] for node in start_nodes: dfs(g.getVertex(node)) #打印结果 for str in paths: for char in str: print(char,end=' ') print()
def topo_sort_bfs(g:Graph): #建立入度表 in_degrees = {} for v in g: if v.id not in in_degrees: in_degrees[v.id] = 0 for nbr in v.getConnections(): in_degrees[nbr.id] = in_degrees.get(nbr.id,0) + 1 # print(in_degrees) #找起始节点 queue = [] for key,value in in_degrees.items(): if value == 0: queue.append(key) #拓扑排序 tuopu = [] while queue: cur_id = queue.pop(0) tuopu.append(cur_id) for nbr in g.getVertex(cur_id).getConnections(): in_degrees[nbr.id] = in_degrees.get(nbr.id) - 1 if in_degrees[nbr.id] == 0: queue.append(nbr.id) #返回结果 return tuopu if len(tuopu) == len(g.getVertices()) else []
def createBoard(size=8): game = Graph() for row in range(size): for col in range(size): ID = (row * size) + col pos = moves(row, col, size) for i in pos: nid = (i[0] * size) + i[1] game.addEdge(ID, nid) return game
def generate_connected_weighted_undirected_graph(number_of_vertices: int, maximum_edge_weight: int, edges_per_vertex: int): graph = Graph() indexes = [index for index in range(number_of_vertices)] for index in indexes: for neighbor_vertex_index in choices(indexes, k=randrange(1, min(number_of_vertices, edges_per_vertex))): graph.addEdge(index, neighbor_vertex_index, randrange(1, maximum_edge_weight)) graph.addEdge(neighbor_vertex_index, index, randrange(1, maximum_edge_weight)) return graph
def knightGraph( size ): """在每个格子上 knightGraph 函数调用 genLegalMoves 辅助函数来创建一个当 前这个格子上骑士所有合法移动的列表。 所有的合法移动都被转换为图上的边。""" knightGrh = Graph() for row in range(size): for col in range(size): location = posToNodeId( row, col, size ) legalList = genLegalMoves( row, col, size) for legal in legalList: legal_loc = posToNodeId(legal[0], legal[1], size) knightGrh.addEdge(location, legal_loc) return knightGrh
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile,'r') # create buckets of words that differ by one letter for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i+1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1,word2) return g
def buildGraph(wordFile): d = {} g = Graph() wfile = open(wordFile, 'r') # create buckets of words that differ by one letter for line in wfile: word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def test_model(self): number_of_vertices, maximum_edge_weight, edges_per_vertex = (10, 10, 3) # graph = RandomGraphGenerator.generate_connected_weighted_undirected_graph(number_of_vertices, # maximum_edge_weight, # edges_per_vertex) graph = Graph() graph.addEdge(0, 1, 1) graph.addEdge(1, 0, 1) graph.addEdge(0, 2, 2) graph.addEdge(2, 0, 2) thorup = ThorupModel(graph) thorup.construct_minimum_spanning_tree(KruskalMstAlgorithm) thorup.construct_other_data_structures() result = thorup.find_shortest_paths(0) self.assertEquals([0, 1, 2], result)
def spawn_tree(source_graph: Graph) -> Graph: union_find_nodes = [ UnionFindNode(i) for i in range(source_graph.numVertices) ] sorted_edges = KruskalMstAlgorithm.sorts_edges_by_weights(source_graph) msb_minimum_spanning_tree = Graph() while sorted_edges: # msb_minimum_spanning_tree.numVertices < ((source_graph.numVertices - 1) * 2): edge = sorted_edges.pop(0) source_id = UnionFindStructureTarjan\ .find(union_find_nodes[edge.source]).item target_id = UnionFindStructureTarjan\ .find(union_find_nodes[edge.target]).item if source_id != target_id: msb_minimum_spanning_tree.addEdge(source_id, target_id, edge.weight) msb_minimum_spanning_tree.addEdge(target_id, source_id, edge.weight) UnionFindStructureTarjan.union(union_find_nodes[source_id], union_find_nodes[target_id]) return msb_minimum_spanning_tree
#!/usr/bin/env python import argparse import re import subprocess, sys, os from pythonds import Queue, Graph, Vertex vertices = [] consumes = Graph() is_consumed = Graph() blacklisted_modules_id = [] class MyVertex(Vertex): WHITE = 0 GRAY = 1 BLACK = 2 def __init__(self,num): self.color = MyVertex.WHITE super().__init__(num) def bfs(graph, start, debug=False): """ Breadth First Search (BFS) Given a node in a graph, BFS will find all nodes connected to this node. The distance between nodes is measured in HOPS. It will find all nodes at distance 'k' before finding any nodes at a further distance. It will return the full list of connected nodes. PseudoCode: BFS(G,s) for each vertex u in V[G] - {s} do state[u] = WHITE
else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1,word2) return g line = "pool cool fool foil fail " word = line[:-1] d = {} g = Graph() for i in range(len(word)): bucket = word[:i] + '_' + word[i+1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1,word2)
# O(V) pq.buildHeap([(v.getDistance(), v) for v in G]) while not pq.isEmpty(): closest = pq.delMin() for n in closest.getConnections(): newCost = closest.getWeight(n) if n in pq and newCost < n.getDistance(): n.setPred(closest) n.setDistance(newCost) pq.decreaseKey(n, newCost) return G g = Graph() g.addVertex(0) g.addVertex(1) g.addVertex(2) g.addVertex(3) g.addEdge(0, 1, 10) g.addEdge(1, 0, 10) g.addEdge(0, 2, 6) g.addEdge(2, 0, 6) g.addEdge(0, 3, 5) g.addEdge(3, 0, 5) g.addEdge(1, 3, 15) g.addEdge(3, 1, 15) g.addEdge(2, 3, 4) g.addEdge(3, 2, 4)
# O(V) pq.buildHeap([(v.getDistance(), v) for v in g]) while not pq.isEmpty(): # O(logV) * O(V) = O(V*logV) closest = pq.delMin() for n in closest.getConnections(): new_distance = closest.getDistance() + closest.getWeight(n) if new_distance < n.getDistance(): n.setDistance(new_distance) n.setPred(closest) # O(E*logV) pq.decreaseKey(n, new_distance) g = Graph() g.addVertex(0) g.addVertex(1) g.addVertex(2) g.addVertex(3) g.addEdge(0, 1, 10) g.addEdge(0, 2, 6) g.addEdge(0, 3, 5) g.addEdge(1, 3, 15) g.addEdge(2, 3, 4) d = dijsktras(g, g.getVertex(0)) print('Distances from {}: '.format(0), end="\n") print("********************") for v in d: print('Distance to {}: {}'.format(v.getId(), d[v]))
def dfs_modified(g, start, visited, s): visited.append(start) for v in g.getVertex(start).getConnections(): if v.id not in visited: dfs_modified(g, v.id, visited, s) s.append(start) def topological_sort(g, n): visited = [] s = [] for i in range(n): if i not in visited: dfs_modified(g, i, visited, s) print(s[::-1]) g = Graph() g.addEdge(5, 2) g.addEdge(5, 0) g.addEdge(4, 0) g.addEdge(4, 1) g.addEdge(2, 3) g.addEdge(3, 1) topological_sort(g, 6)
distance[v][v] = 0 for n in v.getConnections(): distance[v][n] = v.getWeight(n) for k in g: for i in g: for j in g: distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) print_shortest_distance(distance, g) def print_shortest_distance(d, g): for i in d: for j in g: print(f"{i.getId()} --> {j.getId()} {d[i][j]}") g = Graph() g.addVertex(0) g.addVertex(1) g.addVertex(2) g.addVertex(3) g.addEdge(0, 1, 5) g.addEdge(0, 3, 10) g.addEdge(1, 2, 3) g.addEdge(2, 3, 1) floyd_warshall(g)
from pythonds import Graph, Vertex def dfs(g, start, visited=None): if not visited: visited = [] visited.append(start) for v in g.getVertex(start).getConnections(): if v.id not in visited: dfs(g, v.id, visited) return visited g = Graph() for i in range(1, 7): g.addVertex(i) g.addEdge(1,2) g.addEdge(1,3) g.addEdge(2,4) g.addEdge(2,5) g.addEdge(3,5) g.addEdge(3,6) a = dfs(g, 1) print(a)
from pythonds import Graph import timeit from algorithms import Prims from Stats import Display graph = Graph() Display.creategraph(Display, graph) v = graph.getVertex(1) testing = 10 exe = 0 exe2 = 0 # Prim 1 for i in range(testing): start_time = timeit.default_timer() Prims.prim1(Prims, graph, v) time = timeit.default_timer() - start_time exe += time average = exe / testing print("Prim 1 took:", average, 'on average') ''' # Prim 2 for x in range(testing): start_time = timeit.default_timer() Prims.prim2(Prims, graph, v) time = timeit.default_timer() - start_time exe2 += time average = exe2 / testing print("Prim 2 took:", average, 'on average')
else: d[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2) return g line = "pool cool fool foil fail " word = line[:-1] d = {} g = Graph() for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.addEdge(word1, word2)
if t not in self.vertList: self.addVertex(t) self.vertList[f].addNeighbor(self.vertList[t], cost) def getVertices(self): return self.vertList.keys() def __contains__(self, key): return key in self.vertList def __iter__(self): return iter(self.vertList.values()) #测试 g = Graph() for i in range(4): g.addVertex(i) g.addEdge(0, 1, 5) g.addEdge(0, 2, 4) g.addEdge(1, 2, 3) g.addEdge(1, 3, 3) g.addEdge(2, 4, 1) g.addEdge(2, 5, 2) # for v in g: # print(v) # print(g.getVertex(1)) ''' 2.图的遍历(非强连通图也可以) 2.1 BFS
if newDist < nextV.getDistance(): nextV.setDistance(newDist) nextV.setPred(curV) pq.decreaseKey(nextV,newDist) #这个方法应该是内部调用了percUp(),有调整堆的味道 #初始化图 v = ['u','v','x','w','y','z'] #无向图一定要这样创建吗? edge = [('u','v',2),('u','w',5),('u','x',1), ('v','u',2),('v','x',2),('v','w',3), ('x','u',1),('x','v',2),('x','w',3),('x','y',1), ('w','v',2),('w','u',5),('w','x',3),('w','y',1),('w','z',5), ('y','x',1),('y','w',1),('y','z',1), ('z','w',5),('z','y',1)] g = Graph() g.addVertex(v for v in v) for cur,nbr,weight in edge: g.addEdge(cur, nbr, weight) # print(g.getVertex('w')) # #测试 # dijkstra(g,g.getVertex('u')) # for v in v[1:]: # print('u到%s的最短距离:%i' % (v,g.getVertex(v).getDistance())) ''' 4.最小生成树 注:同Dijkstra算法很相似 '''