forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Depth_First_Search.php
81 lines (69 loc) · 1.75 KB
/
Depth_First_Search.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Depth First Search implementation in PHP
<?php
class Node
{
public $name;
public $linked = array();
public function __construct($name)
{
$this -> name = $name;
}
public function link_to(Node $node, $also = true)
{
if (!$this -> linked($node))
$this -> linked[] = $node;
if ($also)
$node -> link_to($this, false);
return $this;
}
private function linked(Node $node)
{
foreach ($this->linked as $l)
{
if ($l -> name === $node -> name)
return true;
}
return false;
}
public function not_visited_nodes($visited_names)
{
$ret = array();
foreach ($this -> linked as $l)
{
if (!in_array($l -> name, $visited_names)) $ret[] = $l;
}
return $ret;
}
}
/* Building Graph */
$root = new Node('root');
foreach (range(1, 6) as $v)
{
$name = "node{$v}";
$$name = new Node($name);
}
$root -> link_to($node1) -> link_to($node2);
$node1 -> link_to($node3) -> link_to($node4);
$node2 -> link_to($node5) -> link_to($node6);
$node4 -> link_to($node5);
/* Searching Path */
function dfs(Node $node, $path = '', $visited = array())
{
$visited[] = $node -> name;
$not_visited = $node -> not_visited_nodes($visited);
if (empty($not_visited))
{
echo 'path : ' . $path . ' -> ' . $node -> name . PHP_EOL;
return;
}
foreach ($not_visited as $n)
dfs($n, $path . ' -> ' . $node -> name, $visited);
}
dfs($root);
/*
OUTPUT:
path : -> root -> node1 -> node3
path : -> root -> node1 -> node4 -> node5 -> node2 -> node6
path : -> root -> node2 -> node5 -> node4 -> node1 -> node3
path : -> root -> node2 -> node6
*/