Depth
Depth
Depth-first search (DFS) is a fundamental algorithm used in graph traversal and searching. It explores
as far as possible along each branch before backtracking. Here's a high-level overview of how DFS
works:
Visit the vertex: Mark the vertex as visited, and perform any necessary operations on it.
Explore adjacent vertices: Move to an adjacent vertex that hasn't been visited yet. If all adjacent
vertices have been visited, backtrack to the previous vertex.
Repeat steps 2 and 3 recursively: Continue visiting vertices and exploring their adjacent vertices
recursively until all reachable vertices have been visited.
In this implementation, graph is represented as an adjacency list, where each vertex maps to a list of
its neighboring vertices. The function dfs takes the graph, the starting vertex, and a set of visited
vertices (initially empty). It recursively visits each vertex and its neighbors, marking them as visited
and performing any processing required for each vertex.
DFS is commonly used in various applications such as finding connected components, cycle
detection, pathfinding, and solving puzzles like mazes.
A -- B -- C
| | |
D -- E -- F
Here's how DFS would traverse this graph starting from vertex A:
Start at vertex A.
Now, backtrack from C. Since all of C's neighbors are visited, backtrack further to B.
Now, backtrack from F. Since all of F's neighbors are visited, backtrack further to E.
Since all of A's neighbors are visited, the DFS traversal is complete.
void dfs(int v) { /*
depth first search of a graph beginning with vertex v.*/ node—pointer w;
visited[v]
printf("%5d", v) ;
for (w = graph[v]; w; w if (!visited[w->vertex])
dfs(w->vertex);
TRUE ;
w->link)
}