我找到了这个用于 PHP 的拓扑排序函数:
来源:http://www.calcatraz.com/blog/php-topological-sort-function-384/
function topological_sort($nodeids, $edges) {
$L = $S = $nodes = array();
foreach($nodeids as $id) {
$nodes[$id] = array('in'=>array(), 'out'=>array());
foreach($edges as $e) {
if ($id==$e[0]) { $nodes[$id]['out'][]=$e[1]; }
if ($id==$e[1]) { $nodes[$id]['in'][]=$e[0]; }
}
}
foreach ($nodes as $id=>$n) { if (empty($n['in'])) $S[]=$id; }
while (!empty($S)) {
$L[] = $id = array_shift($S);
foreach($nodes[$id]['out'] as $m) {
$nodes[$m]['in'] = array_diff($nodes[$m]['in'], array($id));
if (empty($nodes[$m]['in'])) { $S[] = $m; }
}
$nodes[$id]['out'] = array();
}
foreach($nodes as $n) {
if (!empty($n['in']) or !empty($n['out'])) {
return null; // not sortable as graph is cyclic
}
}
return $L;
}
这段话看起来很简短、易懂。关于输入问题,我的输出中会有重复的行 - 可以查看http://codepad.org/thpzCOyn。
一般而言,如果我使用array_unique()
函数去掉重复元素,排序就没问题了。
我用两个实例测试了这个函数,排序本身没有问题。
那么,我应该直接在结果上调用array_unique()
吗?