Depth First Search | Graph Traversals | DAA


Graph Traversals

There are a number of approaches used for solving problems on graphs. One of the most important approaches is based on the notion of systematically visiting all the vertices and edges of a graph. The reason for this is that these traversals impose a type of tree structure (or generally a forest) on the graph, and trees are usually much easier to reason about than general graphs.

Depth First Search

This is another technique that can be used to search the graph. Choose a vertex as a root and form a path by starting at a root vertex by successively adding vertices and edges. This process is continued until no possible path can be formed. If the path contains all the vertices then the tree consisting of this path is the DFS tree. Otherwise, we must add other edges and vertices. For this move back from the last vertex that is met in the previous path and find whether it is possible to find a new path starting from the vertex just met. If there is such a path continue the process above. If this cannot be done, move back to another vertex and repeat the process. The whole process is continued until all the vertices are met. This method of search is also called backtracking.
Example: Use a depth-first search to find a spanning tree of the following graph.

Depth First Search | Graph Traversals | DAA
Depth First Search | Graph Traversals | DAA

Algorithm:

  DFS(G,s)
{
T = {s};
Traverse(s);
}
Traverse(v)
{
for each w adjacent to v and not yet in T
{
T = T U {w}; //put edge {v,w} also
Traverse (w);
}
}

Analysis:

The complexity of the algorithm is greatly affected by the Traverse function we can write its running time in terms of the relation T(n) = T(n-1) + O(n), here O(n) is for each vertex at almost all the vertices are checked (for-loop). At each recursive call, a vertex is decreased. Solving this we can find that the complexity of an algorithm is O(n^2 ). Also from the aggregate analysis, we can write the complexity as O(E+V) because the traverse function is invoked V times maximum and for loop executes O(E) times in total.

Breadth-First Search

Comments

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming