深度优先搜索返回错误的值

时间:2013-11-09 13:14:10

标签: php depth-first-search

class Graph 
{
    protected $_len = 0;
    protected $_g = array();
    protected $_visited = array();

    public function __construct()
    {
        $this->_g = array(
            array(0, 0, 0, 1, 0, 0 ,0),
            array(1, 0, 0, 0, 0, 0 ,0),
            array(1, 0, 0, 0, 0, 0 ,0),
            array(0, 0, 0, 0, 1, 1 ,0),
            array(0, 0, 0, 0, 0, 0 ,1),
            array(0, 0, 0, 0, 0, 0 ,1),
            array(0, 0, 0, 0, 0, 0 ,0),
        );

        $this->_len = count($this->_g);

        $this->_initVisited();
    }

    protected function _initVisited()
    {
        for ($i = 0; $i < $this->_len; $i++) {
            $this->_visited[$i] = 0;
        }
    }

    public function depthFirst($vertex)
    {
        $this->_visited[$vertex] = 1;
        echo $vertex . "\n";
        for ($i = 0; $i < $this->_len; $i++) {
            if ($this->_g[$vertex][$i] == 1 && !$this->_visited[$i]) {
                $this->depthFirst($i);
            }
        }
    }
}

$g = new Graph();
$g->depthFirst(1);

我想找到此图的拓扑顺序 输出为1 0 3 4 6 5。它缺少数字2。在这种情况下,图中有两个起点。 点(1,0)和点(2,0)

我该如何解决这个问题?

0 个答案:

没有答案