-
Notifications
You must be signed in to change notification settings - Fork 0
/
BreadthSearch.php
69 lines (54 loc) · 1.5 KB
/
BreadthSearch.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
<?php
/**
* Created by IntelliJ IDEA.
* User: leonardoalbuquerque
* Date: 29/05/15
* Time: 09:41
*/
class BreadthSearch {
private $buffer = [];
private $output = [];
private $matrix = [];
private $needle;
public function __construct($matrix){
$this->matrix = $matrix;
}
/**
* @param $needle
* @param $matrix
*/
public function doBreathSearch($needle){
$this->needle = $needle;
$this->addNeedleAsFirstElement();
while(!$this->isBufferEmpty()){
foreach($this->matrix[$this->buffer[0]] as $node => $nodeIsConnected){
if($nodeIsConnected && !$this->nodeWasVisited($node)){
$this->addNode($node);
}
}
$this->removeActualElementFromBuffer();
}
return $this->output;
//$this->showOutput();
}
private function addNeedleAsFirstElement(){
$this->buffer = [$this->needle];
$this->output = [$this->needle];
}
private function isBufferEmpty(){
return sizeof($this->buffer) == 0 ;
}
private function nodeWasVisited($node){
return in_array($node,$this->buffer) || in_array($node,$this->output);
}
private function addNode($node){
$this->buffer[] = $node;
$this->output[] = $node;
}
private function removeActualElementFromBuffer(){
array_shift($this->buffer);
}
private function showOutput(){
print_r($this->output);
}
}