使用PHP代码实现迪杰特斯拉算法

class DijkstraCommand extends CConsoleCommand{

    public function run($args)

    {

        @set_time_limit(0);

        @ini_set(‘memory_limit’, ‘2048M’);

        //构造数据结构

        $arcs = array(

            array(0,7,9,999,999,14),

            array(7,0,10,15,999,999),

            array(9,10,0,11,999,2),

            array(999,15,11,0,6,999),

            array(999,999,999,6,0,9),

            array(14,999,2,999,9,0)

        );

        $shortestPath = array();//最短路径值

        $checked = array();//已检查的点

        $path = array();//路径

        $dots = count($arcs);//点的数量

        for ($v = 0; $v < $dots; $v++){

            $checked[$v] = 0;

            $path[$v] = 0;

            $shortestPath[$v] = $arcs[0][$v];

        }

        for ($i = 0; $i < $dots; $i++){

            $min = 999;

            //选最短的点

            for ($w = 0; $w < $dots; $w++){

                if (!$checked[$w])

                {

                    if ($shortestPath[$w] < $min){

                        $v = $w;

                        $min = $shortestPath[$w];

                    }

                }

            }

            $checked[$v] = 1;

            //更新最短路径

            for ($w = 0; $w < $dots; $w++){

                if (!$checked[$w] && ($min + $arcs[$v][$w] < $shortestPath[$w])) {

                    $shortestPath[$w] = $min + $arcs[$v][$w];

                    $path[$w] = $v;

                }

            }

        }

        foreach($path as $key =>$value){

            $trail = “1”;

            if($value > 0){

                $preValue = $value;

                while($value > 0){

                    if($path[$value] > 0){

                        $trail .= “->”.($path[$value]+1);

                    }

                    $value = $path[$value];

                }

                $trail .= “->”.($preValue+1);

            }

            $trail .= “->”.($key+1);

            echo “The trail is “.$trail.” and distances is “.$shortestPath[$key].”\n”;

        }

    }

}

点赞