sending an email through gmail using python

How to implement Depth First Search in Graph?

Depth-First Search is a fundamental algorithm used for traversing and exploring graphs. Below, I’ll outline the steps and provide a Python code implementation for DFS:
Step 1: Introduction to DFS and Graph Representation:
 Briefly explain what DFS is and its purpose in graph traversal.
 Introduce the concept of a graph and different ways to represent it (e.g., adjacency list, adjacency matrix).
Step 2: Implementing the Graph:
 Code the graph representation using an adjacency list.
 Show how to add vertices and edges to the graph.

class Graph:
def __init__(self):
    self.graph = {}
def add_vertex(self, vertex):
    self.graph[vertex] = []
    def add_edge(self, u, v):
    self.graph[u].append(v)
    self.graph[v].append(u) # For an undirected graph

Step 3: Implementing Depth-First Search (DFS)
 Code the DFS algorithm using a recursive approach.
 Explain the importance of visited nodes to avoid infinite loops in graphs containing cycles.

def dfs_recursive(graph, start, visited):
    if start not in visited:
        print(start, end=' ')
        visited.add(start)
    for neighbor in graph[start]:
        dfs_recursive(graph, neighbor, visited)

Step 4: Traversing the Graph with DFS
 Create a graph instance and add vertices and edges to it.
 Perform DFS on the graph and display the traversal order.

if __name__ == "__main__":
    g = Graph()
    # Add vertices and edges to the graph
    g.add_vertex(0)
    g.add_vertex(1)
    g.add_vertex(2)
    g.add_vertex(3)
    g.add_edge(0, 1)
    g.add_edge(0, 2)
    g.add_edge(1, 2)
    g.add_edge(2, 0)
    g.add_edge(2, 3)
    g.add_edge(3, 3)
    print("DFS Traversal (Starting from vertex 2):")
    visited_nodes = set()
    dfs_recursive(g.graph, 2, visited_nodes)

Step 5: Walkthrough of the DFS Execution
 Explain the step-by-step execution of DFS on the provided graph.
 Highlight the visited nodes and the order in which they were visited.

Step 6: Conclusion and Recap
 Summarize the key points of DFS and its importance in graph traversal.
 Recap the steps of the DFS algorithm and the code implementation.