在2个节点之间查找无向图中的所有可能路径

时间:2014-12-28 23:22:03

标签: php graph

我是php的新手,我正在做一个关于无向图的项目。 我写了一个函数来找出这种情况下两个节点(A& G)之间的最短路径。 代码就在下面。我想修改代码,以便我可以列出A-G之间的所有可能路径,所以我在函数中添加一行并尝试使其变为递归

$this->findTheShortestPath($vertex, $destination);

但结果却变成了无限循环。但我明白为什么:(有没有人知道发生了什么?或者有谁知道如何修改代码,以便它可以列出我们所有的路径? 非常感谢

<?PHP
class Graph

{
    protected $graph;
    protected $visited = array();

public function __construct($graph)
{
    $this->graph = $graph;
}


// find least number of hops (edges) between 2 nodes
// (vertices)
public function findTheShortestPath($origin, $destination)
{
    // mark all nodes as unvisited
    foreach ($this->graph as $vertex => $adj) {
        $this->visited[$vertex] = false;
    }

    // create an empty queue
    $q = new SplQueue();

    // enqueue the origin vertex and mark as visited
    $q->enqueue($origin);
    $this->visited[$origin] = true;

    // this is used to track the path back from each node
    $path          = array();
    $path[$origin] = new SplDoublyLinkedList();
    $path[$origin]->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP);

    $path[$origin]->push($origin);

    // while queue is not empty and destination not found

    // print_r($q);
    while (!$q->isEmpty() && $q->bottom() != $destination) {

        $t = $q->dequeue();

        if (!empty($this->graph[$t])) {

            foreach ($this->graph[$t] as $vertex) {

                if (!$this->visited[$vertex]) {

                    $q->enqueue($vertex);
                    $this->visited[$vertex] = true;
                    // add vertex to current path
                    $path[$vertex] = clone $path[$t];
                    $path[$vertex]->push($vertex);
                    //$this->findTheShortestPath($vertex, $destination);
                }
            }

        }

    }

    if (isset($path[$destination])) {
        echo "$origin to $destination in ", count($path[$destination]) - 1, " hops \n";
        $sep = '';
        foreach ($path[$destination] as $vertex) {
            echo $sep, $vertex;
            $sep = '->';
        }
        echo "n";
    } else {
        echo "No route from ", $origin, " to ", $destination, "\n";
    }
}




}

$graph = array(
'A' => array(
    'B',
    'C',
    'F'
),
'B' => array(
    'A',
    'C',
    'E'
),
'C' => array(
    'A',
    'B',
    'D',
    'F'
),
'D' => array(
    'C',
    'F'
),
'E' => array(
    'B',
    'F'
),
'F' => array(
    'A',
    'C',
    'D',
    'E',
    'G'
),
'G' => array(
    'F'
)
);

$g = new Graph($graph);

// least number of hops between D and C
$g->findTheShortestPath('A', 'G');

?>

0 个答案:

没有答案