def createLinkedList(n): g = WeightedGraph() for i in range(1, n+1): g.addNode(createLabel(i)) nodes = g.getAllNodes() for i in range(len(nodes)-1): nodes[i].neighbors[nodes[i+1]] = 1 return g
def __init__(self): NineTailModel.__init__(self) # Invoke superclass constructor # Create a graph vertices = [x for x in range(NUMBER_OF_NODES)] graph = WeightedGraph(vertices, getWeightedEdges()); # Obtain a BSF tree rooted at the target node self.tree = graph.getShortestPath(511)
def createLinkedList(n: int) -> WeightedGraph: graph = WeightedGraph() prevNode = None for i in range(0, n): newNode = graph.addNode(i) if prevNode is not None: graph.addWeightedEdge(prevNode, newNode, 1) prevNode = newNode return graph
def createLinkedList(n): graph = WeightedGraph() for newNode in range(0, n) graph.addNode(newNode) nodelist = graph.getAllNodes() nodelistlength = len(nodelist) for num in range(nodelistlength-1): graph.addWeightedEdge(nodelist[num], nodelist[num+1], 1) return graph
def createRandomCompleteWeightedGraph(n: int) -> WeightedGraph: graph = WeightedGraph() for i in range(0, n): graph.addNode(i) for node in graph.getAllNodes(): for neighbor in graph.getAllNodes(): if node is not neighbor: weight = random.randint(0, n) graph.addWeightedEdge(node, neighbor, weight) return graph
def createRandomCompleteWeightedGraph(n): g = WeightedGraph() for i in range(1, n + 1): g.addNode(createLabel(i)) nodes = g.getAllNodes() for i in nodes: x = nodes.index(i) suggested = nodes[:x] + nodes[x + 1:] for j in suggested: randomWeight = randint(1, 15) g.addDirectedEdge(i, j, randomWeight) return g
def createRandomCompleteWeightedGraph(n): g = WeightedGraph() for i in range(1,n+1): g.addNode(createLabel(i)) nodes = g.getAllNodes() for i in nodes: x = nodes.index(i) # Make a list including all values but the current suggestedList = nodes[:x]+nodes[x+1:] for j in suggestedList: randomWeight = randint(1, 15) g.addDirectedEdge(i, j, randomWeight) return g
def createLinkedList(n): """Makes a weighted graph with n nodes, each having a single edge to the next node of uniform weight.""" graph = WeightedGraph() for i in range(n): graph.addNode(i) if i == 0: continue graph.addWeightedEdge(i-1, i, 1) return graph
def createLinkedList(n): linkedgraph = WeightedGraph() i = 0 while (i < n): linkedgraph.addNode(i) i += 1 j = 1 while (j < (n)): linkedgraph.addWeightedEdge(linkedgraph.nodesList[j - 1], linkedgraph.nodesList[j], 1) j += 1 return linkedgraph
def createRandomCompleteWeightedGraph(n): graph = WeightedGraph() lst = [] for num in range(n): randomNum = random.randint(0, n); if randomNum not in lst: lst.append(randomNum) graph.addNode(num) nodelist = graph.getAllNodes() for node in nodelist: for node2 in range(n): if node != node2: randomWeight = random.randint(1, (n*n)) graph.addWeightedEdge(node, node2, randomWeight) return graph
def createLinkedList(n : int, g : Graph) -> Graph: isWG = isinstance(g, WeightedGraph) if len(g) != 0: # Create new graph if input is not empty g = WeightedGraph() if isWG else Graph() for i in range(n): g.addNode(i) nodes = sorted(g.getAllNodes()) prev = nodes.pop(0) while len(nodes) != 0: curr = nodes.pop() if isWG: g.addWeightedEdge(prev, curr, 1) else: g.addUndirectedEdge(prev, curr) prev = curr return g
def createRandomCompleteWeightedGraph(n): """Makes a complete weighted graph where every node has an edge to every other node with randomly assigned weights.""" graph = WeightedGraph() for i in range(n): graph.addNode(i) for i in range(n): for j in range(n): if i == j: continue graph.addWeightedEdge(i, j, random.choice(range(1, n))) return graph
def createRandomCompleteWeightedGraph(n): randgraph = WeightedGraph() i = 0 while (i < n): randgraph.addNode(i) i += 1 i = 0 while (i < n): j = 0 while (j < n): if i != j: x = randgraph.nodesList[i] y = randgraph.nodesList[j] z = random.randint(1, max(10, n / 2)) randgraph.addWeightedEdge(x, y, z) j += 1 i += 1 return randgraph
def MSTPrim(graph: WeightedGraph, root: Any) -> WeightedGraph: """ Prim's algorithm to creating an MST from a weighted graph - a greedy algorithm taking all accessible edges from the currently considered vertices into account :param graph: a weighted graph of which we extract an MST from :param root: the first node to consider :return: an MST of the graph """ vertices = graph.adjacency_list.keys() mst = WeightedGraph() priority = {} parent = {} for vertex in vertices: priority[vertex] = max(graph.weights.values()) # Acts as infinity parent[vertex] = None priority[root] = 0 q = MinPriorityQueue() for vertex in vertices: q.insert(vertex, priority[vertex]) while not q.is_empty(): node = q.extract_min() u = node.value u_weight = node.priority mst.add_vertex(u) if parent[u] is not None: mst.add_weighted_edge(u, parent[u], u_weight) for v in graph.adjacency_list[u]: if v in q and graph.weights[(u, v)] < priority[v]: priority[v] = graph.weights[( u, v)] # update to the correct weight q.update_priority(v, priority[v]) # update to the correct weight parent[v] = u return mst
queue.append(w) res = [] if pre[self._t] == -1: return res cur = self._t while cur != self._s: res.append(cur) cur = pre[cur] res.append(self._s) return res[::-1] if __name__ == "__main__": filename = '../network.txt' network = WeightedGraph(filename, directed=True) maxflow = MaxFlow(network, 0, 3) print(maxflow.result()) for v in range(network.V): for w in network.adj(v): print('{}-{} : 流量:{} / 容量:{}'.format(v, w, maxflow.flow(v, w), network.get_weight(v, w))) print('=' * 30) filename = '../network2.txt' network = WeightedGraph(filename, directed=True) maxflow = MaxFlow(network, 0, 5)
cc = CC(G) print(cc.ccount) if (cc.ccount > 1): return edges = [] for v in range(G.V): for w in G.adj(v): if v < w: edges.append(WeightedEdge(v, w, G.get_weight(v, w))) edges = sorted(edges, key=lambda key: key.weight) uf = UF(self._G.V) for edge in edges: v = edge.v w = edge.w if uf.isConnected(v, w): continue else: uf.union(v, w) self._mst.append(edge) def result(self): return self._mst if __name__ == '__main__': filename = '../g.txt' g = WeightedGraph(filename) kruskal = Kruskal(g) print(kruskal.result())
[3, 5, 1003], [4, 2, 1663], [4, 3, 599], [4, 5, 533], [4, 7, 1260], [4, 8, 864], [4, 10, 496], [5, 0, 2097], [5, 3, 1003], [5, 4, 533], [5, 6, 983], [5, 7, 787], [6, 5, 983], [6, 7, 214], [7, 4, 1260], [7, 5, 787], [7, 6, 214], [7, 8, 888], [8, 4, 864], [8, 7, 888], [8, 9, 661], [8, 10, 781], [8, 11, 810], [9, 8, 661], [9, 11, 1187], [10, 2, 1435], [10, 4, 496], [10, 8, 781], [10, 11, 239], [11, 8, 810], [11, 9, 1187], [11, 10, 239] ] # Create a graph graph1 = WeightedGraph(vertices, edges) # Obtain a minimum spanning tree tree1 = graph1.getMinimumSpanningTree() print("Total weight is " + str(tree1.getTotalWeight())) tree1.printTree() # Create vertices and edges vertices = [x for x in range(5)] edges = [ [0, 1, 2], [0, 3, 8], [1, 0, 2], [1, 2, 7], [1, 3, 3], [2, 1, 7], [2, 3, 4], [2, 4, 5], [3, 0, 8], [3, 1, 3], [3, 2, 4], [3, 4, 6], [4, 2, 5], [4, 3, 6] ]
[3, 5, 1003], [4, 2, 1663], [4, 3, 599], [4, 5, 533], [4, 7, 1260], [4, 8, 864], [4, 10, 496], [5, 0, 2097], [5, 3, 1003], [5, 4, 533], [5, 6, 983], [5, 7, 787], [6, 5, 983], [6, 7, 214], [7, 4, 1260], [7, 5, 787], [7, 6, 214], [7, 8, 888], [8, 4, 864], [8, 7, 888], [8, 9, 661], [8, 10, 781], [8, 11, 810], [9, 8, 661], [9, 11, 1187], [10, 2, 1435], [10, 4, 496], [10, 8, 781], [10, 11, 239], [11, 8, 810], [11, 9, 1187], [11, 10, 239] ] # Create a graph graph1 = WeightedGraph(vertices, edges) print("The number of vertices in graph1: " + str(graph1.getSize())) print("The vertex with index 1 is " + graph1.getVertex(1)) print("The index for Miami is " + str(graph1.getIndex("Miami"))) print("The edges for graph1: ") graph1.printWeightedEdges() # Create vertices and edges vertices = [x for x in range(5)] edges = [ [0, 1, 2], [0, 3, 8], [1, 0, 2], [1, 2, 7], [1, 3, 3], [2, 1, 7], [2, 3, 4], [2, 4, 5], [3, 0, 8], [3, 1, 3], [3, 2, 4], [3, 4, 6], [4, 2, 5], [4, 3, 6] ]
] # Create edges edges = [[0, 1, 807], [0, 3, 1331], [0, 5, 2097], [1, 0, 807], [1, 2, 381], [1, 3, 1267], [2, 1, 381], [2, 3, 1015], [2, 4, 1663], [2, 10, 1435], [3, 0, 1331], [3, 1, 1267], [3, 2, 1015], [3, 4, 599], [3, 5, 1003], [4, 2, 1663], [4, 3, 599], [4, 5, 533], [4, 7, 1260], [4, 8, 864], [4, 10, 496], [5, 0, 2097], [5, 3, 1003], [5, 4, 533], [5, 6, 983], [5, 7, 787], [6, 5, 983], [6, 7, 214], [7, 4, 1260], [7, 5, 787], [7, 6, 214], [7, 8, 888], [8, 4, 864], [8, 7, 888], [8, 9, 661], [8, 10, 781], [8, 11, 810], [9, 8, 661], [9, 11, 1187], [10, 2, 1435], [10, 4, 496], [10, 8, 781], [10, 11, 239], [11, 8, 810], [11, 9, 1187], [11, 10, 239]] # Create a graph graph1 = WeightedGraph(vertices, edges) # Obtain a shortest path tree1 = graph1.getShortestPath(5) tree1.printAllPaths() # Display shortest paths from Houston to Chicago print("Shortest path from Houston to Chicago: ") path = tree1.getPath(11) print(path) # Create vertices and edges vertices = [x for x in range(5)] edges = [[0, 1, 2], [0, 3, 8], [1, 0, 2], [1, 2, 7], [1, 3, 3], [2, 1, 7], [2, 3, 4], [2, 4, 5], [3, 0, 8], [3, 1, 3], [3, 2, 4], [3, 4, 6], [4, 2, 5], [4, 3, 6]]
] # Create edges edges = [[0, 1, 807], [0, 3, 1331], [0, 5, 2097], [1, 0, 807], [1, 2, 381], [1, 3, 1267], [2, 1, 381], [2, 3, 1015], [2, 4, 1663], [2, 10, 1435], [3, 0, 1331], [3, 1, 1267], [3, 2, 1015], [3, 4, 599], [3, 5, 1003], [4, 2, 1663], [4, 3, 599], [4, 5, 533], [4, 7, 1260], [4, 8, 864], [4, 10, 496], [5, 0, 2097], [5, 3, 1003], [5, 4, 533], [5, 6, 983], [5, 7, 787], [6, 5, 983], [6, 7, 214], [7, 4, 1260], [7, 5, 787], [7, 6, 214], [7, 8, 888], [8, 4, 864], [8, 7, 888], [8, 9, 661], [8, 10, 781], [8, 11, 810], [9, 8, 661], [9, 11, 1187], [10, 2, 1435], [10, 4, 496], [10, 8, 781], [10, 11, 239], [11, 8, 810], [11, 9, 1187], [11, 10, 239]] # Create a graph graph1 = WeightedGraph(vertices, edges) # Obtain a minimum spanning tree tree1 = graph1.getMinimumSpanningTree() print("Total weight is " + str(tree1.getTotalWeight())) tree1.printTree() # Create vertices and edges vertices = [x for x in range(5)] edges = [[0, 1, 2], [0, 3, 8], [1, 0, 2], [1, 2, 7], [1, 3, 3], [2, 1, 7], [2, 3, 4], [2, 4, 5], [3, 0, 8], [3, 1, 3], [3, 2, 4], [3, 4, 6], [4, 2, 5], [4, 3, 6]] # Create a graph graph2 = WeightedGraph(vertices, edges)
def createRandomCompleteWeightedGraph(n : int) -> Graph: return populateGraph(WeightedGraph(), n)
if argv[1] == "graph": l_10000 = createLinkedList(large, Graph()) l_100 = createLinkedList(small, Graph()) print(BFTRecLinkedList(l_10000), end = "\n\n") print(BFTRecLinkedList(l_100), end = "\n\n") print(BFTIterLinkedList(l_10000)) elif argv[1] == "directed": g = createRandomDAGIter(medium) if visualize: print(g) for func in [TopSort.Kahns, TopSort.mDFS]: arr = func(g) print(" Node Count: {} | {}".format(len(arr), arr)) elif argv[1] == "weighted": for g in [createLinkedList(small, WeightedGraph()), createRandomCompleteWeightedGraph(small)]: if visualize: print(g) n = g.getNode(str(randint(0, small-1))) print("Dijkstras Map for Node {}: {}".format(n, dijkstras(n))) print() elif argv[1] == "grid": dim = tiny g = createRandomGridGraph(dim) if visualize: print(g) sourceNode = g.graphToArr()[0][0] destNode = g.graphToArr()[dim-1][dim-1] print(astar(sourceNode, destNode)) else: print("Invalid argument")
x2 = x2.split(", ") for a in range(len(x2)): x2[a] = eval(x2[a]) edges.append([]) edges[len(edges) - 1].append(x1) edges.append([]) edges[len(edges) - 1].append(x2) else: x = x.split(", ") for a in range(len(x)): x[a] = eval(x[a]) edges.append([]) edges[len(edges) - 1].append(x) fin.close() g = WeightedGraph(nodes, edges) mst = g.getMinimumSpanningTree() wht = mst.getTotalWeight() for i in range(num): print("Vertex "+str(i)+":", end = " ") for j in range(len(edges)): if edges[j][0] == i: print(edges[j], end = " ") print("")
from WeightedGraph import WeightedGraph from Chapter11ShortestaPath.python.Floyd import Floyd if __name__ == '__main__': filename = '../wg.txt' g = WeightedGraph(filename, directed=True) floyd = Floyd(g) if not floyd.has_neg_cycle(): for v in range(g.V): strings = [] for w in range(g.V): strings.append(str(floyd.dist_to(v, w))) print(' '.join(strings)) else: print('exist negative cycle') filename = '../wg2.txt' g = WeightedGraph(filename, directed=True) floyd = Floyd(g) if not floyd.has_neg_cycle(): for v in range(g.V): strings = [] for w in range(g.V): strings.append(str(floyd.dist_to(v, w))) print(' '.join(strings)) else: print('exist negative cycle')
for vertex in vertices: q.insert(vertex, priority[vertex]) while not q.is_empty(): node = q.extract_min() u = node.value u_weight = node.priority mst.add_vertex(u) if parent[u] is not None: mst.add_weighted_edge(u, parent[u], u_weight) for v in graph.adjacency_list[u]: if v in q and graph.weights[(u, v)] < priority[v]: priority[v] = graph.weights[( u, v)] # update to the correct weight q.update_priority(v, priority[v]) # update to the correct weight parent[v] = u return mst if __name__ == "__main__": graph = WeightedGraph() graph.add_vertices(["A", "B", "C", "D", "E", "F"]) graph.add_weighted_edges([("A", "B", 4), ("A", "D", 3), ("A", "E", 3), ("B", "C", 10), ("B", "D", 1), ("B", "E", 2), ("C", "E", 8), ("C", "F", 8), ("D", "E", 1), ("E", "F", 9)]) print(graph) print(MSTPrim(graph, "c"))