Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created November 10, 2019 22:41
Show Gist options
  • Save adrianosferreira/ccf6c9fa134e485385917c2a828b15f4 to your computer and use it in GitHub Desktop.
Save adrianosferreira/ccf6c9fa134e485385917c2a828b15f4 to your computer and use it in GitHub Desktop.
Max and min components in a Graph using Breadth First Search in PHP
<?php
/**
* Created by PhpStorm.
* User: adriano
* Date: 09/11/19
* Time: 18:18
*/
class Vertex {
private $data;
private $edges = [];
private $visited = false;
public function __construct( $data ) {
$this->data = $data;
}
public function getEdges() {
return $this->edges;
}
public function addEdge( Vertex $edge ) {
$this->edges[ $edge->getData() ] = $edge;
}
public function getData() {
return $this->data;
}
public function setVisited() {
$this->visited = true;
}
public function isVisited() {
return $this->visited;
}
}
function buildGraph( $gb ) {
$graph = [];
foreach( $gb as $key => $pair ) {
$firstVertex = $graph[ $pair[0] ] ?? new Vertex( $pair[0] );
$secondVertex = $graph[ $pair[1] ] ?? new Vertex( $pair[1] );
if ( ! isset( $firstVertex->getEdges()[ $secondVertex->getData() ] ) ) {
$firstVertex->addEdge( $secondVertex );
}
if ( ! isset( $secondVertex->getEdges()[ $firstVertex->getData() ] ) ) {
$secondVertex->addEdge( $firstVertex );
}
if ( ! isset( $graph[ $firstVertex->getData() ] ) ) {
$graph[ $firstVertex->getData() ] = $firstVertex;
}
if ( ! isset( $graph[ $secondVertex->getData() ] ) ) {
$graph[ $secondVertex->getData() ] = $secondVertex;
}
}
return $graph;
}
/*
* Complete the componentsInGraph function below.
*/
function componentsInGraph($gb) {
$graph = buildGraph( $gb );
$queue = [];
$smallest = 0;
$highest = 0;
foreach( $graph as $vertex ) {
$numOfNodes = 0;
if ( $vertex->isVisited() ) {
continue;
}
$queue[] = $vertex;
$numOfNodes++;
$currentVertex = $vertex;
while( $queue ) {
foreach( $currentVertex->getEdges() as $edge ) {
if ( $edge->isVisited() ) {
continue;
}
$edge->setVisited();
$numOfNodes++;
$queue[] = $edge;
}
array_shift( $queue );
$currentVertex->setVisited();
$currentVertex = current( $queue );
}
if ( ! $highest || $highest < $numOfNodes ) {
$highest = $numOfNodes;
}
if ( ! $smallest || $smallest > $numOfNodes ) {
$smallest = $numOfNodes;
}
}
print $smallest . ' ' . $highest;
}
componentsInGraph(
[
[ 5, 56 ],
[ 4, 51 ],
[ 2, 53 ],
[ 8, 52 ],
[ 5, 43 ],
[ 2, 80 ],
[ 5, 47 ],
[ 4, 79 ],
[ 3, 75 ],
[ 1, 67 ],
[ 7, 61 ],
[ 2, 57 ],
[ 5, 47 ],
[ 4, 63 ],
[ 10, 79 ],
[ 1, 57 ],
[ 4, 42 ],
[ 8, 79 ],
[ 6, 53 ],
[ 3, 74 ],
[ 7, 60 ],
[ 10, 79 ],
[ 5, 46 ],
[ 3, 50 ],
[ 6, 57 ],
[ 8, 71 ],
[ 6, 74 ],
[ 10, 44 ],
[ 9, 80 ],
[ 7, 59 ],
[ 7, 74 ],
[ 6, 55 ],
[ 3, 77 ],
[ 3, 53 ],
[ 5, 50 ],
[ 9, 70 ],
[ 4, 72 ],
[ 5, 73 ],
[ 6, 70 ],
[ 7, 46 ],
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment