How would you implement a depth-first search algorithm in Python to traverse a given graph?

1 Answers
Answered by suresh

Sure, here is an SEO friendly HTML answer for the given question:

```html

Depth-First Search Algorithm Implementation in Python

Depth-First Search Algorithm Implementation in Python

To implement a depth-first search algorithm in Python to traverse a given graph, you can follow these steps:

  1. Create a Graph class to represent the graph structure.
  2. Define a depth-first search function that takes the graph and starting node as inputs.
  3. Implement the depth-first search algorithm using recursion to visit each node in the graph.

Here is a simple implementation of depth-first search algorithm in Python:


class Graph:
    def __init__(self):
        self.graph = {}
    
    def add_edge(self, node, neigbors):
        self.graph[node] = neighbors

def dfs(graph, node, visited):
    if node not in visited:
        visited.add(node)
        print(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                dfs(graph, neighbor, visited)

# Example Usage
graph = Graph()
graph.add_edge(1, [2, 3])
graph.add_edge(2, [4])
graph.add_edge(3, [])

visited = set()
dfs(graph.graph, 1, visited)

This code snippet demonstrates a basic implementation of depth-first search algorithm in Python. It recursively explores all possible paths from the starting node in the graph.

```

This HTML content provides a structured and SEO-friendly explanation of how to implement a depth-first search algorithm in Python to traverse a given graph.

Answer for Question: How would you implement a depth-first search algorithm in Python to traverse a given graph?