Last active
November 9, 2019 18:33
-
-
Save adrianosferreira/85a10603c3b234e8ef991aa3795dbc75 to your computer and use it in GitHub Desktop.
Traversing a Graph using depth first search in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: adriano | |
* Date: 09/11/19 | |
* Time: 13:18 | |
*/ | |
class Node { | |
private $data; | |
private $visited = false; | |
private $edges = []; | |
public function __construct( $data ) { | |
$this->data = $data; | |
} | |
public function getData() { | |
return $this->data; | |
} | |
public function getEdges(): array { | |
return $this->edges; | |
} | |
public function setEdges( array $edges ) { | |
$this->edges = $edges; | |
} | |
public function markVisited() { | |
$this->visited = true; | |
} | |
public function isVisited() { | |
return $this->visited; | |
} | |
} | |
class Graph { | |
private $nodes; | |
public function __construct( $nodes ) { | |
$this->nodes = $nodes; | |
} | |
public function getNodes() { | |
return $this->nodes; | |
} | |
public function traverseDFS(): void { | |
$stack = [ current( $this->nodes ) ]; | |
$currentVertex = current( $stack ); | |
$currentVertex->markVisited(); | |
echo 'Visited:' . $currentVertex->getData() . PHP_EOL; | |
while( $stack ) { | |
$visitedEdges = 0; | |
foreach( $currentVertex->getEdges() as $edge ) { | |
if ( $edge->isVisited() ) { | |
$visitedEdges++; | |
continue; | |
} | |
$edge->markVisited(); | |
echo 'Visited:' . $edge->getData() . PHP_EOL; | |
$stack[] = $edge; | |
$currentVertex = $edge; | |
break; | |
} | |
if ( ! $currentVertex->getEdges() || $visitedEdges === count( $currentVertex->getEdges() ) ) { | |
array_pop( $stack ); | |
end( $stack ); | |
$currentVertex = current( $stack ); | |
} | |
} | |
} | |
} | |
$a = new Node( 'A' ); | |
$b = new Node( 'B' ); | |
$c = new Node( 'C' ); | |
$d = new Node( 'D' ); | |
$e = new Node( 'E' ); | |
$f = new Node( 'F' ); | |
$a->setEdges( [ $b, $c ] ); | |
$b->setEdges( [ $d ] ); | |
$d->setEdges( [ $e, $f ] ); | |
$graph = new Graph( [ $a, $b, $c, $d, $e, $f ] ); | |
$graph->traverseDFS(); | |
$test = 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment