How to reconstruct paths from a multi-path Dijkstra?

后端 未结 2 1482
轮回少年
轮回少年 2021-01-21 07:25

I am currently writing a PHP library for graphs. I have already implemented a single-path Dijkstra\'s algorithm successfully, but now struggle with implementing a multi-path ver

2条回答
  •  盖世英雄少女心
    2021-01-21 07:57

    Actually, a modified DFS function I named "enumerate" solved this question. For posterity's sake, here is the code I used to turn the output of the multi-path Dijkstra into an array of paths:

    /**
     * Returns all shortest paths to $dest from the origin vertex $this->start in the graph.
     *
     * @param string $dest ID of the destination vertex
     *
     * @return array An array containing the shortest path and distance
     */
    public function get($dest)
    {
        $this->paths = [];
        $this->enumerate($dest, $this->start);
    
        return array(
            'paths' => $this->paths,
            'dist' => $this->dist[$dest],
        );
    }
    
    /**
     * Enumerates the result of the multi-path Dijkstra as paths.
     *
     * @param string $source ID of the source vertex
     * @param string $dest   ID of the destination vertex
     */
    private function enumerate($source, $dest)
    {
        array_unshift($this->path, $source);
        $discovered[] = $source;
    
        if ($source === $dest) {
            $this->paths[] = $this->path;
        } else {
            if (!$this->prev[$source]) {
                return;
            }
            foreach ($this->prev[$source] as $child) {
                if (!in_array($child, $discovered)) {
                    $this->enumerate($child, $dest);
                }
            }
        }
    
        array_shift($this->path);
        if (($key = array_search($source, $discovered)) !== false) {
            unset($discovered[$key]);
        }
    }
    

提交回复
热议问题