def buildGraph(wordFile): dic = {} g = Graph() def read_file_line(wordFile): with open(wordFile, 'r') as wfile: while True: blockline = wfile.readline() # 调用readlines()一次读取所有内容并按行返回list if blockline: yield blockline.strip() else: return # create buckets of words that differ by one letter for line in read_file_line(wordFile): word = line[:-1] for i in range(len(word)): bucket = word[:i] + '_' + word[i + 1:] if bucket in dic: dic[bucket].append(word) else: dic[bucket] = [word] # add vertices and edges for words in the same bucket for bucket in dic.keys(): for word1 in dic[bucket]: for word2 in dic[bucket]: if word1 != word2: g.addEdge(word1, word2) return g
def buildGraphFromAdjacencyList(graph): g = Graph() for vertex, neighbors in graph.items(): for neighbor in neighbors: g.addEdge(vertex, neighbor) return g
def knightGraph(bdSize): ktGraph = Graph() for row in range(bdSize): for col in range(bdSize): nodeId = posToNodeId(row, col, bdSize) newPositions = genLegalMoves(row, col, bdSize) for e in newPositions: nid = posToNodeId(e[0], e[1], bdSize) ktGraph.addEdge(nodeId, nid) return ktGraph
def test_dijkstra(self): # Example from https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm g = Graph() g.addEdge(1, 2, 7) g.addEdge(1, 3, 9) g.addEdge(2, 3, 10) g.addEdge(1, 6, 14) g.addEdge(2, 4, 15) g.addEdge(3, 6, 2) g.addEdge(3, 4, 11) g.addEdge(4, 5, 6) g.addEdge(5, 6, 9) dist = g.bestPath_Dijkstra(1, 5) self.assertEqual(20, dist)
from graph_adjacency_list import Graph if __name__ == '__main__': graph = Graph(5) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph()
if proposed_dist < shortest_distance[neighbor_node]: shortest_distance[neighbor_node] = proposed_dist previous_node[neighbor_node] = curr_node # work backgrounds through the previous node dict and save path curr = target while curr != source: short_path.insert(0, curr) # insert at beginning of list curr = previous_node[curr] # get previous node short_path.insert(0, curr) # insert the last, source node return (short_path, shortest_distance[target]) adjacency_graph = Graph() ## # adjacency_graph.add_edge('a', 'c', 15) # adjacency_graph.add_edge('b', 't', 1) # adjacency_graph.add_edge('d', 't', 1) # adjacency_graph.add_edge('a', 't', 21) # adjacency_graph.add_edge('b', 'u', 1) # adjacency_graph.add_edge('b', 't', 6) # adjacency_graph.add_edge('u', 't', 2) # adjacency_graph.add_edge('c', 't', 20) # print shortest_path(adjacency_graph, 'a', 't') graph1 = Graph() graph1.add_edge('t', 'a', 5)