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()
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) import sys 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)
return path def _validateVertex(self, v): # throw an ValueError unless 0 <= v < V V = len(self._marked) if v < 0 or v >= V: raise ValueError("vertex {} is not between 0 and {}".format( v, V - 1)) if __name__ == "__main__": from algs4.stdlib import stdio from algs4.graphs.graph import Graph from algs4.stdlib.instream import InStream import sys In = InStream(sys.argv[1]) G = Graph.from_stream(In) s = int(sys.argv[2]) dfs = DepthFirstPaths(G, s) for v in range(G.V()): if dfs.has_path_to(v): stdio.writef("%d to %d: ", s, v) for x in dfs.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)