Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Last active November 9, 2019 18:33
Show Gist options
  • Save adrianosferreira/85a10603c3b234e8ef991aa3795dbc75 to your computer and use it in GitHub Desktop.
Save adrianosferreira/85a10603c3b234e8ef991aa3795dbc75 to your computer and use it in GitHub Desktop.
Traversing a Graph using depth first search in PHP
<?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