return topological_list def dfs_visit(graph: Graph, u: Any, time: int, status: dict, topological_list: LinkedList) -> None: """ Completely explores each vertex connected to the source vertex u, starting from lowest depth :param graph: the graph to perform dfs_visit on :param u: the vertex to recurse down :param time: the time called :return: the time after dfs_visit() completes on the source vertex """ status[u] = 1 # update u to grey time += 1 for v in graph.adjacency_list[u]: if status[v] == 0: dfs_visit(graph, v, time, status, topological_list) status[u] = 2 time += 1 topological_list.insert_first(u) if __name__ == '__main__': graph = DirectedGraph() graph.add_vertices(["a", "b", "c", "d", "e", "f"]) graph.add_edges([("a", "b"), ("a", "d"), ("b", "e"), ("c", "f"), ("d", "b"), ("f", "d")]) print(graph) print(topological_sort(graph))
:return: the time after dfs_visit() completes on the source vertex """ status[u] = 1 # update u to grey time += 1 discovery_time[u] = time for v in graph.adjacency_list[u]: if status[v] == 0: parent[v] = u time = dfs_visit(graph, v, time, status, discovery_time, finish_time, parent) status[u] = 2 time += 1 finish_time[u] = time return time if __name__ == '__main__': graph1 = DirectedGraph() graph1.add_vertices([1, 2, 3, 4, 5, 6, 7]) graph1.add_edges([(1, 2), (1, 4), (1, 7), (2, 3), (2, 4), (3, 1), (3, 4), (5, 4), (5, 6), (6, 3), (6, 5), (7, 1), (7, 4)]) print(graph1) print(str(dfs(graph1)) + "\n") graph2 = DirectedGraph() graph2.add_vertices(["a", "b", "c", "d", "e", "f"]) graph2.add_edges([("a", "b"), ("a", "d"), ("b", "e"), ("c", "f"), ("d", "b"), ("e", "d"), ("f", "d"), ("f", "f")]) print(graph2) print(dfs(graph2))
parent[vertex] = None status[ source] = 1 # initialize source at grey (visited but not explored completely) distance[source] = 0 # the distance from the source to itself is 0 q = Queue() # queue for vertices that need to be explored q.enqueue(source) while not q.is_empty(): u = q.dequeue() for v in graph.adjacency_list[u]: if status[v] == 0: # if vertex v is white status[v] = 1 # update v to grey distance[v] = distance[u] + 1 parent[v] = u q.enqueue(v) status[u] = 2 # we have fully explored u, hence update u to black bfs_traversal.append((u, distance[u], parent[u])) return bfs_traversal if __name__ == '__main__': graph = DirectedGraph() graph.add_vertices(["s", "a", "b", "c", "d", "e", "f"]) graph.add_edges([("s", "a"), ("s", "f"), ("a", "b"), ("a", "e"), ("b", "c"), ("b", "d"), ("c", "d"), ("c", "e"), ("e", "d"), ("e", "f")]) print(graph) print(bfs(graph, "s"))