Esempio n. 1
0
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()
Esempio n. 2
0
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()
Esempio n. 3
0
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()
Esempio n. 4
0
        self._on_stack[v] = False

    def has_cycle(self):
        """Does the digraph have a directed cycle?

        :returns: true if there is a cycle, false otherwise

        """
        return self._cycle is not None

    def cycle(self):
        """Returns a directed cycle if the digraph has a directed cycle, and
        null otherwise.

        :returns: a directed cycle (as an iterable) if the digraph has a directed cycle, and null otherwise

        """
        return self._cycle


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))

    cyc = DirectedCycle(d)
    print(cyc.cycle())