Python Depth First Search Algorithm
Depth First Search (DFS) is a graph traversal algorithm used for visiting all the vertices of a graph in a depth-wise manner. It starts from the root node and explores as far as possible along each branch before backtracking.
Here's a simple implementation of DFS in Python using an adjacency list to represent a graph:
def dfs(graph, node, visited):
if node not in visited:
print(node, end=' ')
visited.append(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
visited = []
dfs(graph, 'A', visited)
This code will produce the following output:
A B D E F C
Note that the output order may vary depending on the implementation of the adjacency list and the order of neighbors in each node's list. The important thing is that all vertices are visited and processed in a depth-first manner.