Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created November 9, 2019 18:44
Show Gist options
  • Save adrianosferreira/a7090c1c7831e185191e21987d451691 to your computer and use it in GitHub Desktop.
Save adrianosferreira/a7090c1c7831e185191e21987d451691 to your computer and use it in GitHub Desktop.
Traversing a Graph through Breadth 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 {
$queue = [];
$currentVertex = current( $this->getNodes() );
$currentVertex->markVisited();
echo 'Visited: ' . $currentVertex->getData() . PHP_EOL;
$queue[] = $currentVertex;
while( $queue ) {
foreach ( $currentVertex->getEdges() as $edge ) {
echo 'Visited: ' . $edge->getData() . PHP_EOL;
$queue[] = $edge;
}
array_shift( $queue );
$currentVertex = current( $queue );
}
}
}
$a = new Node( 'A' );
$b = new Node( 'B' );
$c = new Node( 'C' );
$d = new Node( 'D' );
$e = new Node( 'E' );
$f = new Node( 'F' );
$g = new Node( 'G' );
$a->setEdges( [ $b, $c ] );
$b->setEdges( [ $d, $e ] );
$d->setEdges( [ $g ] );
$c->setEdges( [ $f ] );
$graph = new Graph( [ $a, $b, $c, $d, $e, $f, $g ] );
$graph->traverseDFS();
$test = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment