Depth first search

As we have seen for the BFS, we can define any starting vertex for the DFS as well. The difference is that for a list of visited nodes, we will use a stack instead of a queue. Other parts of the code will be similar to our BFS code. We will also use the same graph we used for the BFS implementation. The DFS implementation we will implement is an iterative one. Here is the code for it:

function DFS(array &$graph, int $start, array $visited): SplQueue { 
$stack = new SplStack;
$path = new SplQueue;

$stack->push($start);
$visited[$start] = 1;

while (!$stack->isEmpty()) {
$node = $stack->pop();
$path->enqueue($node);
foreach ($graph[$node] as $key => $vertex) {
if (!$visited[$key] && $vertex == 1) {
$visited[$key] = 1;
$stack->push($key);
}
}
}

return $path;
}

As mentioned earlier, for a DFS, we have to use a stack instead of a queue as we need the last vertex from the stack instead of the first one (if we have used a queue). For the path part, we use a queue so that we can show the path sequentially during the display. Here is the code to call for our graph $graph:

$path = DFS($graph, 1, $visited); 
while (!$path->isEmpty()) {
echo $path->dequeue()." ";
}

The code will produce the following output:

    1       5       4       6       3       2

For the preceding example, we start from vertex 1, and we will visit vertex 5 first out of the two adjacent vertices with the labels 5 and 2 of vertex 1. Now, vertex 5 has two vertices with labels 4 and 2. Vertex 4 will be visited first as it appears as the first edge from vertex 5 (bearing in mind our left to right direction of visiting nodes). Next, we will visit vertex 6 from vertex 4. Since, we cannot go any further from vertex 6, it will return to vertex 4 and visit the unvisited adjacent vertex with the label 3. When we are at vertex 3, there are two adjacent vertices available from 3. They are labeled as vertex 4 and vertex 2. We already visited vertex 4 earlier, so we cannot revisit it, and we have to visit vertex 2 from vertex 3. Since vertex 2 has three vertices, vertex 3, 5, and 1, and all of them are already visited, we are actually done with our DFS implementation here.

We can pass an extra parameter if we are looking for a specific end vertex from a starting vertex. In the earlier example, we were just getting the adjacent vertex and visiting all of them. For a specific end vertex, we had to match the target vertex with each of our visiting vertex during the iteration of the DFS algorithm.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset