0% found this document useful (0 votes)
8 views

Depth

Uploaded by

sreelakshmy333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Depth

Uploaded by

sreelakshmy333
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Depth-first search

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:

Start at a vertex: Choose a starting vertex to begin the traversal.

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.

Sure, let's illustrate depth-first search (DFS) with a simple example.

Consider this undirected

A -- B -- C
| | |
D -- E -- F
Here's how DFS would traverse this graph starting from vertex A:

Start at vertex A.

Visit vertex A and mark it as visited.

Explore one of A's neighbors, say B.

Visit vertex B and mark it as visited.

From B, explore one of its neighbors, say C.

Visit vertex C and mark it as visited.

Now, backtrack from C. Since all of C's neighbors are visited, backtrack further to B.

From B, explore another unvisited neighbor, say D.

Visit vertex D and mark it as visited.

From D, explore one of its neighbors, say E.

Visit vertex E and mark it as visited.

From E, explore one of its neighbors, say F.

Visit vertex F and mark it as visited.

Now, backtrack from F. Since all of F's neighbors are visited, backtrack further to E.

From E, backtrack further to D.

From D, backtrack further to B.

From B, backtrack further to A.

Since all of A's neighbors are visited, the DFS traversal is complete.

The order of visiting the vertices in this DFS traversal is: A, B, C, D, E, F.

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)
}

You might also like