The basic idea behind Depth First Traversal is to mark each vertex as visited and then recursively explore all the unvisited vertices adjacent to the current vertex. By keeping track of visited vertices, this algorithm ensures that each vertex is visited only once.
The pseudocode for Depth First Traversal is as follows:
DepthFirstTraversal(vertex v, visited):
visited[v] = true // mark the current vertex as visited
print v // print or process the current vertex
for each adjacent vertex u of v:
if visited[u] is false: // check if u has not been visited
DepthFirstTraversal(u, visited) // recursively explore the unvisited vertex
In the above pseudocode, v
represents the current vertex being visited, and visited
is an array or hash table used to keep track of visited vertices.
Implementing Depth First Traversal in different programming languages follows a similar approach. Here’s an example implementation in Python:
def depth_first_traversal(graph, start, visited):
visited[start] = True
print(start)
for neighbor in graph[start]:
if not visited[neighbor]:
depth_first_traversal(graph, neighbor, visited)
# Example usage
graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
}
visited = [False] * len(graph)
depth_first_traversal(graph, 2, visited)
The above code demonstrates Depth First Traversal on a simple graph represented as an adjacency list. The graph
dictionary represents the vertices and their adjacent vertices. The visited
array is used to keep track of visited vertices.
In conclusion, Depth First Traversal is a powerful algorithm used to explore graphs in a systematic manner. It is widely used in various applications, including maze solving, topological sorting, and finding connected components in a graph.
#DFS #GraphTraversal