May 2017
Intermediate to advanced
340 pages
8h 16m
English
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] ...Read now
Unlock full access