def main(): """Creates an edge-weighted graph from the given input file and prints it.""" if len(sys.argv) > 1: stream = InStream(sys.argv[1]) G = EdgeWeightedGraph.from_stream(stream) print(G)
def main(): """Creates an edge-weighted graph from an input file, runs Kruskal's algorithm on it, and prints the edges of the MST and the sum of the edge weights.""" if len(sys.argv) > 1: stream = InStream(sys.argv[1]) G = EdgeWeightedGraph.from_stream(stream) mst = KruskalMST(G) for e in mst.edges(): print(e) print("{:.5f}".format(mst.weight()))
def main(): """Unit tests the DirectedDFS data type.""" G = Digraph.from_stream(InStream(None)) sources = Bag() for i in range(1, len(sys.argv)): s = int(sys.argv[i]) sources.add(s) dfs = DirectedDFS(G, *sources) print("Reachable vertices:") for v in range(0, G.V()): if dfs.is_marked(v): print(v, end=" ") print()
def main(): if len(sys.argv) == 3: stream = InStream(sys.argv[1]) G = EdgeWeightedGraph.from_stream(stream) s = int(sys.argv[2]) sp = DijkstraUndirectedSP(G, s) for t in range(G.V()): if sp.has_path_to(t): print("{} to {} ({:.2f}) ".format(s, t, sp.dist_to(t)), end='') for e in sp.path_to(t): print(e, end=' ') print() else: print("{} to {} no path\n".format(s, t))
def main(args): stream = InStream(args[0]) G = Digraph.from_stream(stream) scc = KosarajuSharirSCC(G) # number of connected components m = scc.count() print("{} strong components".format(m)) # compute list of vertices in each strong component components = [Queue() for i in range(m)] for v in range(G.V()): components[scc.id(v)].enqueue(v) # print results for i in range(m): for v in components[i]: print(str(v), end=" ") print()
def main(args): stream = InStream(args[0]) s = int(args[1]) G = EdgeWeightedDigraph.from_stream(stream) sp = BellmanFordSP(G, s) #print negative cycle if sp.has_negative_cycle(): for e in sp.negative_cycle(): print(e) #print shortest paths else: for v in range(G.V()): if sp.has_path_to(v): print("{} to {} ({}) ".format(s, v, sp.dist_to(v))) for e in sp.path_to(v): print("{}\t".format(e), end='') print() else: print("{} to {} no path".format(s, v))
def main(): """ Creates an EdgeWeightedDigraph from input file. Runs DijkstraSP on the graph with the given source vertex. Prints the shortest path from the source vertex to all other vertices. """ if len(sys.argv) == 3: stream = InStream(sys.argv[1]) G = EdgeWeightedDigraph.from_stream(stream) s = int(sys.argv[2]) sp = DijkstraSP(G, s) for t in range(G.V()): if sp.has_path_to(t): print("{} to {} ({:.2f}) ".format(s, t, sp.dist_to(t)), end='') for e in sp.path_to(t): print(e, end=' ') print() else: print("{} to {} no path\n".format(s, t))
def __init__(self, filename, delimiter): """Initializes a graph from a file using the specified delimiter. Each line in the file contains the name of a vertex, followed by a list of the names of the vertices adjacent to that vertex, separated by the delimiter. :param filename: the name of the file :param delimiter: the delimiter between fields """ self._st = BinarySearchST() # string -> index # First pass builds the index by reading strings to associate # distinct strings with an index stream = InStream(filename) while not stream.isEmpty(): a = stream.readLine().split(delimiter) for i in range(len(a)): if not self._st.contains(a[i]): self._st.put(a[i], self._st.size()) stdio.writef("Done reading %s\n", filename) # inverted index to get keys in an array self._keys = [None] * self._st.size() # index -> string for name in self._st.keys(): self._keys[self._st.get(name)] = name # second pass builds the graph by connecting first vertex on each # line to all others self._graph = Graph(self._st.size()) # the underlying graph stream = InStream(filename) while stream.hasNextLine(): a = stream.readLine().split(delimiter) v = self._st.get(a[0]) for i in range(1, len(a)): w = self._st.get(a[i]) self._graph.add_edge(v, w)
def main(args): stream = InStream(args[0]) G = Digraph.from_stream(stream) tc = TransitiveClosure(G) # print header print(" ", end="") for v in range(G.V()): print("{x:3d}".format(x=v), end="") print() print("--------------------------------------------") # print transitive closure for v in range(G.V()): print("{x:3d}: ".format(x=v), end="") for w in range(G.V()): if tc.reachable(v, w): print(" T", end="") else: print(" ", end="") print()
path = Stack() x = v while self._dist_to[x] != 0: path.push(x) x = self._edgeTo[x] path.push(x) return path if __name__ == "__main__": import sys from itu.algs4.stdlib import stdio from itu.algs4.graphs.graph import Graph from itu.algs4.stdlib.instream import InStream In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) bfs = BreadthFirstPath(G, s) for v in range(G.V()): if bfs.has_path_to(v): stdio.writef("%d to %d (%d): ", s, v, bfs.dist_to(v)) for x in bfs.path_to(v): if x == s: stdio.write(x) else: stdio.writef("-%i", x) stdio.writeln() else: stdio.writef("%d to %d (-): not connected\n", s, v)
rev = Digraph(self._V) for v in range(self._V): for w in self.adj(v): rev.add_edge(w, v) return rev def __repr__(self): """ Returns a string representation of this graph. :returns: the number of vertices V, followed by the number of edges E, followed by the V adjacency lists """ s = ["{} vertices, {} edges\n".format(self._V, self._E)] for v in range(self._V): s.append("%d : " % (v)) for w in self._adj[v]: s.append("%d " % (w)) s.append("\n") return ''.join(s) if __name__ == '__main__': # Create stream from file or the standard input, # depending on whether a file name was passed. stream = sys.argv[1] if len(sys.argv) > 1 else None d = Digraph.from_stream(InStream(stream)) print(d)