...

/

Solution: Depth-First Graph Traversal

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 visited
visited = [False] * (len(my_graph.graph))
# Create a stack for DFS
stack = []
# Result string
result = ""
# Push the source
stack.append(source)
while stack:
# Pop a vertex from stack
source = 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 it
while my_graph.graph[source] is not None:
data = my_graph.graph[source].vertex
if not visited[data]:
stack.append(data)
my_graph.graph[source] = my_graph.graph[source].next
return result
# Main to test the above program
if __name__ == "__main__":
V = 5
g = 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 ...

Access this course and 1400+ top-rated courses and projects.