PHP:递归地在字母图中查找单词

时间:2016-12-30 10:40:23

标签: php algorithm recursion graph

我有这样的图表:

enter image description here

现在,让我们说我正在寻找一个单词 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);
        }
    }
}

现在,我不知道如何处理递归返回,以便让我得到我想要的结果。

1 个答案:

答案 0 :(得分:-1)

可以使用Master theorem解决。 假设$node->id是您想在结果数组中看到的数字,递归可能看起来像

public function find(string $word, array $nodes = null): array
{

    $firstLetter = mb_substr($word, 0, 1);
    $rest = mb_substr($word, 1);

    if (empty($nodes)) {
        //top level call, start to search across all nodes
        $nodes = $this->letters;
    }

    $result = [];

    foreach ($nodes as $node) {
        if ($node->letter === $firstLetter) {
            if (empty($rest)) {
                //exit recursion
                $result[] = [$node->id];
            } else {
                //recursively search rest of the string
                $branches = $this->find($rest, $node->neighbours);
                if (!empty($branches)) {
                    foreach ($branches as $branch) {
                        $result[] = array_merge([$node->id], $branch);
                    }
                }
            }
        }
    }
    return $result;
}