Solution: Depth-First Graph Traversal
In this review, we learn how to write code for the depth-first traversal of a graph.
We'll cover the following...
Solution:
def dfs(my_graph, source):"""Function to print a DFS of graph:param graph: The graph:param source: starting vertex:return: returns the traversal in a string"""# Mark all the vertices as not visitedvisited = [False] * (len(my_graph.graph))# Create a stack for DFSstack = []# Result stringresult = ""# Push the sourcestack.append(source)while stack:# Pop a vertex from stacksource = stack.pop()if not visited[source]:result += str(source)visited[source] = True# Get all adjacent vertices of the popped vertex source.# If a adjacent has not been visited, then push itwhile my_graph.graph[source] is not None:data = my_graph.graph[source].vertexif not visited[data]:stack.append(data)my_graph.graph[source] = my_graph.graph[source].nextreturn result# Main to test the above programif __name__ == "__main__":V = 5g = Graph(V)g.add_edge(0, 1)g.add_edge(0, 2)g.add_edge(1, 3)g.add_edge(1, 4)print(dfs(g, 0))
Explanation
The depth-first graph algorithm uses the idea of backtracking. We exhaustively search all the nodes by going ahead, if possible, or else by backtracking.
Here, the word ‘backtrack’ means to move forward as long as there are no more nodes in the current path, then move backward on the same path to find nodes to traverse.
In the following solution, we have used a stack
to implement depth-first graph traversal.
Time complexity
Let ...