Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 14

Depth first search

Depth first works by selecting one vertex V of G as a start vertex; V is marked visited. Then each unvisited vertex adjacent to V is searched in turn using depth first search recursively. This process continues until a dead end (i.e.,) a vertex with no adjacent unvisited vertices is encountered. At a deadend, the algorithm backsup one edge to the vertex it came from and tries to continue visiting unvisited vertices from there

To implement the depth first search perform the following


 Step 1- choose any node in the graph. Designate it as the search node and mark it as visited  Step 2- using the adjacency matrix of the graph, find a node adjacent to the search node that has not been visited yet. Desiginate this as the new search node and mark it as visited.  Step 3- repeat step 2 using the new search node. If no nodes satisfying(2) can be found, return to the previous search node and continue from there.

 Step 4- when a return to the previous search node in (3) is impossible, the search from the orginally choosen search node is complete  Step 5- if the graph still contains unvisited nodes, choose any node that has not been visited and repeat step(1) through(4)

Routine for depth first search


Void DFS(vertex V) {
Visited[v]=true; For each W adjacent to v If(!visited[W]) Dfs(W) }

Example
A B C D A B A 0 1 1 1

B C D C

IMPLEMENTATION
 Let A be the source vertex. Mark it to be visited  Find the immediate adjacent unvisited vertex B of A . Mark it to be visited.  From B the next adjacent vertex is D . Mark it as visited  From D the next unvisited vertex is C . Mark it as visited.

Depth first spanning tree


A B

Application of depth first search


 To check whether the undirected graph is connected or not  To check whether the connected undirected graph is biconnected or not  To check the a acyclicity of the directed graph

1. Undirected graphs
 A undirected graph is connected if and only if a depth first search starting from any node visits every node
A

B D

ADJACENCY MATRIX
A B C D E A B C D E 0 1 0 1 1 1 0 1 1 0 0 1 0 1 1 1 1 1 0 0 1 0 1 0 0

IMPLEMENTATIONS
 We start vertex A . Then mark A as visited and call DFS(B) recursively, dfs(b) marks B as visited and calls DFS(c) recursively

A B

 Dfs(c) marks C as visited and call dfs(D) recursively. No recursive calls are made to dfs(B) since B is already visited.

 Dfs(D) marks D as visited. Dfs(D) sees A,B,C As Marked so no recursive call is made there, and dfs(D) returns back to dfs(C).

 Dfs(C) calls dfs(E),where E is unseen adjacent vertex to C

A B

 Since all the vertices starting from A are visited, the above graph is said to be connected. If the graph is not connected, then processing all nodes requires reversal calls to dfs, and each generates a tree. This entire collection is a depth first search

You might also like