Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created November 19, 2019 20:43
Show Gist options
  • Save adrianosferreira/ae838d3bcb1171b4176668a224cb29a8 to your computer and use it in GitHub Desktop.
Save adrianosferreira/ae838d3bcb1171b4176668a224cb29a8 to your computer and use it in GitHub Desktop.
Find the nearest clone
<?php
class Node {
public $id;
public $edges = [];
public $colorId;
public function __construct( $id, $colorId ) {
$this->id = $id;
$this->colorId = $colorId;
}
public function setEdge( Node $edge ) {
$this->edges[] = $edge;
}
}
function findShortest( $graph_nodes, $graph_from, $graph_to, $ids, $val ) {
$nodes = [];
$start = null;
for ( $i = 1; $i <= $graph_nodes; $i ++ ) {
$colorId = $ids[ $i - 1 ];
$nodes[ $i ] = new Node( $i, $colorId );
if ( ! $start && $colorId === $val ) {
$start = $nodes[ $i ];
}
}
if ( ! $start ) {
return -1;
}
foreach ( $graph_from as $key => $nodeFrom ) {
$nodeSource = $nodes[ $nodeFrom ];
$nodeTarget = $nodes[ $graph_to[ $key ] ];
$nodeSource->setEdge( $nodeTarget );
$nodeTarget->setEdge( $nodeSource );
}
$queue = [ $start, null ];
$currentNode = $start;
$visitedNodes = [ $start->id => $start ];
$levels[ $currentNode->id ] = 0;
while ( $queue ) {
foreach ( $currentNode->edges as $edge ) {
if ( isset( $visitedNodes[ $edge->id ] ) ) {
continue;
}
$visitedNodes[ $edge->id ] = $edge;
$currentLevel = $levels[ $currentNode->id ] + 1;
if ( $edge->colorId === $val ) {
return $currentLevel;
}
$levels[ $edge->id ] = $currentLevel;
$queue[] = $edge;
}
array_shift( $queue );
$visitedNodes[ $currentNode->id ] = $currentNode;
$currentNode = current( $queue );
}
return - 1;
}
$graph_nodes = 4;
$graph_from = [ 1, 1, 4 ];
$graph_to = [ 2, 3, 2 ];
$ids = [ 1, 2, 1, 1 ];
$val = 6;
findShortest( $graph_nodes, $graph_from, $graph_to, $ids, $val );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment