doucao8982 2016-12-30 10:40
浏览 40

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

I'm having a graph like this:

enter image description here

Now, let's say I'm looking for a word CAT. I'm trying to make a nice code to walk this graph and find a word. I'd like it to find all existing positions of a word, not only first one.

The result for $graph->find('cat') should be:

return [
    [1, 0, 6],
    [1, 2, 3]
];

I have created such code in the past, but it was iterative. This time I'd like to try recursive.

Here's what I have so far:

I call it like this:

// LetterGraph is my own class
$graph = new LetterGraph($nodes);
$graph->find('cat');

And in my LetterGraph class I do the following:

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);
        }
    }
}

Now, I'm not sure how to deal with recursive returns to make it give me the result I want.

  • 写回答

1条回答 默认 最新

  • douwen2072 2016-12-30 11:55
    关注

    It can be solved using Master theorem. Assuming $node->id is the number you want to see in the resulting array, the recursion may look like

    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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题