Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing depth-first graph traversal

I have conflicting information about depth first traversal and could use some help in understanding how to build a program. Given a certain graph, I want to print a sequence of vertices. The user will input a particular node to start the traversal from. I am looking at different examples and I don't understand how the order of the depth-first traversal works. I have the following pseudocode to work with:

public DFS() {
    DFS(v)
    {   num(v) = i ++;
       for all vertices u adjacent to v
       { if num(u) is 0
            attach edge(uv) to edges;
            DFS(u);
        }
    }



depthFirstSearch()
{     for all vertices v
        num(v) = 0;
  edges = null; //vector of all edges
  i=1;
  while there is a vertex v such that num(v) is 0
         DFS(v);
  output edges;
}
like image 544
Raging Java Avatar asked Feb 11 '26 19:02

Raging Java


1 Answers

The key to both of these snippets are the following idea:

check if item found at (v)
if item not found,
   for all vertices u adjacent to v
     depth_first_search(u)

Instead of checking for the end condition at all the node's (v) children (list of u's) right away, you only check for it at the current node v. If the end condition is not met, you apply the same depth first search function starting with the first child of v, u1. Since u1 might also have children, the exact same function will be applied to u1's children before the remainder of v's children are processed, and so on. This is why it is called a depth first search, since your search will first search to the lowest possible set of children in a path before coming back to check the remaining children.

like image 168
Carlos Daniel Gadea Omelchenko Avatar answered Feb 14 '26 08:02

Carlos Daniel Gadea Omelchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!