繁体   English   中英

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

[英]PHP: Finding word in graph of letters recursively

我有一个这样的图表:

在此输入图像描述

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

现在,我不知道如何处理递归返回,以使它给我想要的结果。

它可以使用Master定理来解决。 假设$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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM