1 | <?php |
||
9 | class DirectedGraph |
||
10 | { |
||
11 | /** @var Vertex[] */ |
||
12 | private $vertices = []; |
||
13 | |||
14 | public function __construct(array $vertices) |
||
21 | |||
22 | public function getVertices() |
||
26 | |||
27 | /** |
||
28 | * @param callable|null $comparator Comparator of vertex values |
||
29 | * |
||
30 | * @return array |
||
31 | */ |
||
32 | public function findAllCycles(callable $comparator = null) |
||
33 | { |
||
34 | $cycles = []; |
||
35 | |||
36 | $verticesCount = \count($this->vertices); |
||
37 | foreach ($this->vertices as $vertex) { |
||
38 | $visited = []; |
||
39 | for ($i = 0; $i < $verticesCount; $i++) { |
||
40 | $visited[$i] = false; |
||
41 | } |
||
42 | |||
43 | foreach ($vertex->getNeighbours() as $neighbour) { |
||
44 | $foundCycles = $this->findAllCyclesRecursive($vertex, $neighbour, $visited); |
||
45 | if ($foundCycles) { |
||
46 | $cycles = \array_merge($cycles, $foundCycles); |
||
47 | } |
||
48 | } |
||
49 | } |
||
50 | |||
51 | return $this->sortAndRemoveDuplicateCycles($cycles, $comparator); |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * @param Vertex $needle |
||
56 | * @param Vertex $current |
||
57 | * @param bool[] $visited |
||
58 | * @param mixed[] $currentCycle |
||
59 | * |
||
60 | * @return array|bool |
||
61 | */ |
||
62 | private function findAllCyclesRecursive(Vertex $needle, Vertex $current, &$visited, $currentCycle = []) |
||
63 | { |
||
64 | if ($visited[$current->getIndex()]) { |
||
65 | return false; |
||
66 | } |
||
67 | |||
68 | $currentCycle[] = $current->getValue(); |
||
69 | if ($current === $needle) { |
||
70 | return [$currentCycle]; |
||
71 | } |
||
72 | |||
73 | $cycles = []; |
||
74 | $visited[$current->getIndex()] = true; |
||
75 | foreach ($current->getNeighbours() as $neighbour) { |
||
76 | $foundCycles = $this->findAllCyclesRecursive($needle, $neighbour, $visited, $currentCycle); |
||
77 | if ($foundCycles) { |
||
78 | $cycles = \array_merge($cycles, $foundCycles); |
||
79 | } |
||
80 | } |
||
81 | |||
82 | return $cycles; |
||
83 | } |
||
84 | |||
85 | private function reindex() |
||
93 | |||
94 | /** |
||
95 | * @param mixed[][] $cycles Array of cycles |
||
96 | * @param callable|null $comparator Comparator of vertex values |
||
97 | * |
||
98 | * @return mixed |
||
99 | */ |
||
100 | private function sortAndRemoveDuplicateCycles(array $cycles, callable $comparator = null) |
||
128 | |||
129 | /** |
||
130 | * Scrolls a cycle so that minimal element(according to comparator) is at the beginning of cycle. |
||
131 | * |
||
132 | * @param array $array |
||
133 | * @param callable $comparator |
||
134 | */ |
||
135 | private function scrollCycle(array &$array, callable $comparator) |
||
151 | |||
152 | /** |
||
153 | * @return callable |
||
154 | */ |
||
155 | private function getDefaultComparator() |
||
161 | } |
||
162 |