- <?php
- class Dijkstra
- {
- private $G;
- public function __construct()
- {
- //有向图存储
- $this->G = array(
- array(0,1,2,0,0,0,0),
- array(0,0,0,1,2,0,0),
- array(0,0,0,0,0,2,0),
- array(0,0,0,0,0,1,3),
- array(0,0,0,0,0,0,3),
- array(0,0,0,0,0,0,1),
- array(0,0,0,0,0,0,0),
- );
- }
- public function calculate()
- {
- // 存储已经选择节点和剩余节点
- $U = array(0);
- $V = array(1,2,3,4,5,6);
- // 存储路径上节点距离源点的最小距离
- $d = array();
- //初始化图中节点与源点0的最小距离
- for($i=1;$i<7;$i++)
- {
- if($this->G[0][$i]>0)
- {
- $d[$i] = $this->G[0][$i];
- }
- else
- {
- $d[$i] = 1000000;
- }
- }
- // n-1次循环完成转移节点任务
- for($l=0;$l<6;$l++)
- {
- // 查找剩余节点中距离源点最近的节点v
- $current_min = 100000;
- $current_min_v = 0;
- foreach($V as $k=>$v)
- {
- if($d[$v] < $current_min)
- {
- $current_min = $d[$v];
- $current_min_v = $v;
- }
- }
- //从V中更新顶点到U中
- array_push($U,$current_min_v);
- array_splice($V,array_search($current_min_v,$V),1);
- //更新
- foreach($V as $k=>$u)
- {
- if($this->G[$current_min_v][$u]!=0&&$d[$u]>$d[$current_min_v]+$this->G[$current_min_v][$u])
- {
- $d[$u] = $d[$current_min_v]+$this->G[$current_min_v][$u];
- }
- }
- }
- foreach($d as $k => $u)
- {
- echo $k.'=>'.$u.'<br>';
- }
- }
- }
- ?>
- $D = new Dijkstra;
- $D->calculate();