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 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 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 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
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
#!/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
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')
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算法很相似 '''