Beispiel #1
0
def main():
    file_name = '../resources/tinyDG.txt'
    with open(file_name) as f:
        ints = list()
        for line in f.read().split('\n'):
            ints.append(line)
        vertices, edges = int(ints[0]), int(ints[1])

    graph = Digraph(vertices)
    print(graph)
    inp = ints[
        2:]  # skip first 2 lines in tiny.DG.txt i.e. # of vertices and edges

    for i in range(edges):
        v, w = inp[i].split(' ')
        graph.add_edge(int(v), int(w))
    print(graph)
    s = 2
    dfs = NonrecursiveDirectedDFS(graph, s)
    print(dfs)
    for v in range(graph.get_V()):
        if dfs.marked(v):
            print(f'{s} is connected to {v} ')
        else:
            print(f'{s} not connected to {v}')
def main():
    g = Digraph(13)
    with open("../resources/tinyDAG.txt", ) as f:
        for line in f.readlines():
            vertices = " ".join(line.splitlines()).split(' ')
            if len(vertices) < 2:
                continue
            else:
                v1, v2 = int(vertices[0]), int(vertices[1])
                g.add_edge(v1, v2)
    print(g)
    dfs = DepthFirstOrder(g)
    print(dfs)
    print("v    pre   post")
    print("--------------------")
    for v in range(g.get_V()):
        print(f'{v}     {dfs.pre(v)}     {dfs.post(v)}\n')

    print('Pre-order')
    for v in dfs.preorder_vertices():
        print(f'{v} ', end="")
    print()
    print('Post-order')
    for v in dfs.postorder_vertices():
        print(f'{v} ', end="")
    print()
    print(dfs.postorder_vertices())
    print('Reverse Post-order')
    q1 = dfs.reverse_post()
    for v in q1:
        print(f'{v} ', end="")
def main():
    file_name = '../resources/tinyDG.txt'
    with open(file_name) as f:
        ints = list()
        for line in f.read().split('\n'):
            ints.append(line)
        vertices, edges = int(ints[0]), int(ints[1])

    graph = Digraph(vertices)
    print(graph)
    inp = ints[
        2:]  # skip first 2 lines in tiny.DG.txt i.e. # of vertices and edges

    for i in range(edges):
        v, w = inp[i].split(' ')
        graph.add_edge(int(v), int(w))
    print(graph)

    scc = KosarajuSharirSCC(graph)
    m = scc.count()
    print(f'{m} strong components')
    components = [Queue() for _ in range(m)]
    for v in range(graph.get_V()):
        components[scc.id(v)].put(v)
    for i in range(m):
        for v in components[i].queue:
            print(f'{v} ', end="")
        print()
def main():
    file_name = '../resources/digraph1.txt'
    with open(file_name) as f:
        ints = list()
        for line in f.read().split('\n'):
            ints.append(line)
        vertices, edges = int(ints[0]), int(ints[1])

    graph = Digraph(vertices)
    inp = ints[
        2:]  # skip first 2 lines in tiny.DG.txt i.e. # of vertices and edges

    for i in range(edges):
        v, w = inp[i].split(' ')
        graph.add_edge(int(v), int(w))

    s = 3
    sources = [3, 4, 5]
    # bfs = BreadthFirstDirectedPaths(graph, s)
    bfs = BreadthFirstDirectedPaths(graph, sources=sources)
    print(bfs)
    for v in range(graph.get_V()):
        if bfs.has_path_to(v):
            print(f'{sources} to {v} ({bfs.dist_to(v)})')
            path = bfs.path_to(v)
            while not path.empty():
                x = path.get()
                if x == s or x in sources:
                    print(f'{x}', end="")
                else:
                    print(f'->{x}', end="")
            print()
        else:
            print(f'{s} to {v} (-): not connected.\n')
Beispiel #5
0
class SymbolDigraph:
    def __init__(self, file_name, delimiter=" "):
        self._st = defaultdict(int)

        # First pass builds the index by reading strings to associate
        # distinct strings with an index
        with open(f"../resources/{file_name}.txt", ) as f:
            for line in f.readlines():
                a = " ".join(line.splitlines()).split(delimiter)
                for i in range(len(a)):
                    if a[i] not in self._st:
                        self._st[a[i]] = len(self._st)

        # inverted index to get string keys in an array
        self._keys = ['' for _ in range(len(self._st))]
        for name in self._st.keys():
            self._keys[self._st.get(name)] = name

        # second pass builds the digraph by connecting first vertex on each
        # line to all others
        self._graph = Digraph(len(self._st))
        with open(f"../resources/{file_name}.txt", ) as f:
            for line in f.readlines():
                a = " ".join(line.splitlines()).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 contains(self, s):
        return s in self._st

    def index_of(self, s):
        return self._st.get(s)

    def name_of(self, v):
        self.__validate_vertex(v)
        if isinstance(v, int):
            return self._keys[v]
        else:
            return self._keys[v.item]

    def digraph(self):
        return self._graph

    def __validate_vertex(self, v):
        n = self._graph.get_V()
        if isinstance(v, int):
            if v < 0 or v >= n:
                raise ValueError(f'vertex {v} is not between 0 and {n - 1}')
        else:
            if v.item < 0 or v.item >= n:
                raise ValueError(f'vertex {v} is not between 0 and {n - 1}')

    def __repr__(self):
        return f'<{self.__class__.__name__}(_st={self._st}, _graph={self._graph}, _keys={self._keys})>'
Beispiel #6
0
def main():

    file_name = '../resources/tinyDG.txt'
    with open(file_name) as f:
        ints = list()
        for line in f.read().split('\n'):
            ints.append(line)
        vertices, edges = int(ints[0]), int(ints[1])

    graph = Digraph(vertices)
    # print(graph)
    inp = ints[
        2:]  # skip first 2 lines in tiny.DG.txt i.e. # of vertices and edges
    sources = Bag()
    sources.add(1)
    sources.add(5)
    sources.add(10)

    for i in range(edges):
        v, w = inp[i].split(' ')
        graph.add_edge(int(v), int(w))

    # print(graph)

    # s = 6
    # reachable from single source vertex, s
    # dfs = DirectedDFS(graph, int(s))
    # print(dfs)

    # reachable from many source vertices, sources
    dfs = DirectedDFS(graph, sources)
    # print(dfs)

    for v in range(graph.get_V()):
        if dfs.marked(v):
            print(f'{v} ')
 def __init__(self, g: Digraph):
     self._tc = [DirectedDFS(g, v) for v in range(g.get_V())]