How to reconstruct paths from a multi-path Dijkstra?

后端 未结 2 1483
轮回少年
轮回少年 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]);
        }
    }
    
    0 讨论(0)
  • 2021-01-21 08:20

    Like this? (Pseudocode):

    function output_paths(source, dest, tail) {
    
        if source == dest:
            output([dest] + tail)
    
        for each node in prev[dest]:
            output_paths(source, node, [dest] + tail)
    }
    
    
    output_paths(source=A, dest=J, tail=[])
    
    0 讨论(0)
提交回复
热议问题