Explain what is DFS (Depth First Search) algorithm for a Graph and how does it work?
Explain what is DFS (Depth First Search) algorithm for a Graph and how does it work?
Depth-First Search (DFS) is a fundamental algorithm used for traversing or searching tree or graph data structures. The algorithm starts at a specified root node and explores as far as possible along each branch before backtracking. This method is particularly useful for tasks that require exhaustive searches of all nodes, such as solving mazes, detecting cycles, and finding connected components in a graph.
DFS can be implemented both recursively and iteratively. Here is a step-by-step explanation of how DFS works:
Initialization:
Starting Point:
Traversal:
Backtracking:
Here is the pseudocode for the recursive implementation of DFS:
def DFS(graph, vertex, visited=None):
if visited is None:
visited = set()
visited.add(vertex)
print(vertex) # Process the vertex (e.g., print it)
for neighbor in graph[vertex]:
if neighbor not in visited:
DFS(graph, neighbor, visited)
return visited
Consider the following undirected graph:
0 -- 1 -- 3
| |
2 4
The adjacency list representation of this graph is:
graph = {
'0': ['1', '2'],
'1': ['0', '3', '4'],
'2': ['0'],
'3': ['1'],
'4': ['1']
}
Running DFS starting from vertex '0' would visit the vertices in the following order: 0, 1, 3, 4, 2.
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào