【发布时间】:2017-05-14 16:07:11
【问题描述】:
我有这样的图表:
现在,假设我正在寻找一个词 CAT。我正在尝试编写一个很好的代码来遍历这个图表并找到一个单词。我希望它能找到一个单词的所有现有位置,而不仅仅是第一个。
$graph->find('cat') 的结果应该是:
return [
[1, 0, 6],
[1, 2, 3]
];
我过去创建过这样的代码,但它是迭代的。这次我想试试递归。
这是我目前所拥有的:
我这样称呼它:
// LetterGraph is my own class
$graph = new LetterGraph($nodes);
$graph->find('cat');
在我的 LetterGraph 课程中,我执行以下操作:
public function find(string $word): array {
$result = [];
$firstLetter = mb_substr($word, 0, 1);
foreach ($this->letters as $node) {
if ($node->letter === $firstLetter) {
$result[] = $this->walk($word, [$node]);
}
}
return $result;
}
protected function walk(string $word, array $nodes): array {
$lastNode = end($nodes);
$letterToFind = mb_substr($word, count($nodes), 1);
foreach ($lastNode->neighbours as $neighbour) {
if ($neighbour->letter === $letterToFind) {
// is return okay here?
return $this->walk($word, array_merge($nodes, $neighbour);
}
}
}
现在,我不确定如何处理递归返回以使其得到我想要的结果。
【问题讨论】:
-
如何定义图中的边?
new LetterGraph(['a', 'c', 'a', 't', 'b', 'r', 't']);仅定义节点。 -
是的,我简化了一点。让我们假设每个
$node都可以访问$node->neighbours。
标签: php algorithm recursion graph