From: Andrey Kutejko Date: Sun, 9 Nov 2014 08:28:31 +0000 (+0200) Subject: topological sort algorithm X-Git-Tag: 0.2~7 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=7d22f1cd70189d7b13d1cc30b846f9086abfc545;p=missing-tools.git topological sort algorithm --- diff --git a/src/algorithm.php b/src/algorithm.php new file mode 100644 index 0000000..9873e67 --- /dev/null +++ b/src/algorithm.php @@ -0,0 +1,56 @@ +following, $obj); + } + + private function once($obj) + { + if (in_array($obj, $this->visited)) { + return false; + } else { + $this->visited[] = $obj; + return true; + } + } + + private function visit($obj, $chain) + { + if (in_array($obj, $chain)) { + $chain[] = $obj; + return $chain; + } + + if ($this->once($obj)) { + $chain[] = $obj; + foreach ($this->getFollowing($obj) as $following) { + $loop = $this->visit($following, $chain); + if ($loop !== false) + return $loop; + } + $this->result[] = $obj; + } + return false; + } + + public static function sort($initialNodes, $following) + { + $sort = new self; + $sort->following = $following; + + foreach ($initialNodes as $start) { + $loop = $sort->visit($start, array()); + if ($loop !== false) + return array(false, $loop); + } + return array(true, $sort->result); + } +} +