-
Notifications
You must be signed in to change notification settings - Fork 1
/
DFS.php
45 lines (37 loc) · 939 Bytes
/
DFS.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
ob_start(); // for removing the printf from other files
include 'Graph.php';
ob_end_clean();
/**
* DFS - Depth First Search
* V is the number of vertices.
* E is the number edges.
*
* Time Complexity: O(V + E)
*/
function DFS(&$graph, $s) {
if ($graph->visited[ $s ]) {
return;
}
$graph->visited[ $s ] = true;
echo "$s "; // prosess node s
if (isset($graph->adjacencyList[ $s ])) {
foreach ($graph->adjacencyList[ $s ] as $u => $weight) {
DFS($graph, $u);
}
}
}
// ----------------
// --- Examples ---
// ----------------
define("NL", PHP_SAPI === 'cli' ? "\n" : "<br />"); // define new line feed based on web/cli
$graph = new Graph(); // direcred & unweighted
$graph->addEdge(1, 2);
$graph->addEdge(2, 4);
$graph->addEdge(2, 5);
$graph->addEdge(4, 6);
$graph->addEdge(5, 1);
$graph->addEdge(5, 3);
$s = 2;
printf("DFS(graph, %d) = ", $s);
DFS($graph, $s);