Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

A graph concept

Just a simple graph concept.
<?php

class HappyBirthDay {

    private $sickPatients;
    private $adjacencyList;

    public function __construct(array $adjacencyList, array $sickPatients)
    {
        $this->adjacencyList = $adjacencyList;
        $this->sickPatients  = $sickPatients;
    }

    function isAllowedGuest(int $id, int $depth, array $visited) 
    {
        $visited[] = $id;
        $contacts = $this->adjacencyList[$id];
    
        if ($depth == 0) {
            return true;
        }
        $depth--;
        
        if( array_intersect($contacts, $this->sickPatients) ) {
            return false;
        }
        foreach($contacts as $id ) {
            if(!in_array($id, $visited) && !$this->isAllowedGuest($id, $depth, $visited)) {
                return false;
            }
        }
        return true;
    }
    
    function getAllowedGusets(int $host, int $depth)
    {
        $this->host = $host;
        $allowedGusets = [];
        foreach($this->adjacencyList[$host] as $id) {
            if ($this->isAllowedGuest($id, $depth, [$host]) ) {
                $allowedGusets[] = $id;
            }
        }
        return $allowedGusets;
    }

}


$adjacencyList = [
    1  => [2,3,5,8],
    2  => [1,7],
    3  => [1,4,5],
    4  => [3,10],
    5  => [1,3,6],
    6  => [5,9],
    7  => [2],
    8  => [1,10],
    9  => [6],
    10 => [4,8],
];
$sickPatients = [9,4];
$depth        = 2;
$host         = 1;

$happyBirthDay = new HappyBirthDay($adjacencyList, $sickPatients);
$allowedGusets = $happyBirthDay->getAllowedGusets($host, $depth, []);
echo implode(',', $allowedGusets) . PHP_EOL;
Download...