Tracing and Returning a Path in Depth First Search

前端 未结 4 1961
青春惊慌失措
青春惊慌失措 2021-01-30 09:19

So I have a problem that I want to use depth first search to solve, returning the first path that DFS finds. Here is my (incomplete) DFS function:

    start = pr         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 09:52

    I just implemented something similar in PHP.

    The basic idea behind follows as: Why should I maintain another stack, when there is the call stack, which in every point of the execution reflects the path taken from the entry point. When the algorithm reaches the goal, you simply need to travel back on the current call stack, which results in reading the path taken in backwards. Here is the modified algorithm. Note the return immediately sections.

    /**
     * Depth-first path
     * 
     * @param Node $node        Currently evaluated node of the graph
     * @param Node $goal        The node we want to find
     *
     * @return The path as an array of Nodes, or false if there was no mach.
     */
    function depthFirstPath (Node $node, Node $goal)
    {
        // mark node as visited
        $node->visited = true;
    
        // If the goal is found, return immediately
        if ($node == $goal) {
            return array($node);
        }
    
        foreach ($node->outgoing as $edge) {
    
            // We inspect the neighbours which are not yet visited
            if (!$edge->outgoing->visited) {
    
                $result = $this->depthFirstPath($edge->outgoing, $goal);
    
                // If the goal is found, return immediately
                if ($result) {
                    // Insert the current node to the beginning of the result set
                    array_unshift($result, $node);
                    return $result;
                }
            }
        }
    
        return false;
    }
    

提交回复
热议问题