迪科斯彻算法(Dijkstra)

 

  1. <?php  
  2. class Dijkstra   
  3. {  
  4.     private $G;  
  5.     public function __construct()  
  6.     {     
  7.         //有向图存储  
  8.         $this->G = array(  
  9.             array(0,1,2,0,0,0,0),  
  10.             array(0,0,0,1,2,0,0),  
  11.             array(0,0,0,0,0,2,0),  
  12.             array(0,0,0,0,0,1,3),  
  13.             array(0,0,0,0,0,0,3),  
  14.             array(0,0,0,0,0,0,1),  
  15.             array(0,0,0,0,0,0,0),  
  16.         );  
  17.     }  
  18.       
  19.     public function calculate()  
  20.     {  
  21.         // 存储已经选择节点和剩余节点  
  22.         $U = array(0);  
  23.         $V = array(1,2,3,4,5,6);  
  24.           
  25.         // 存储路径上节点距离源点的最小距离  
  26.         $d = array();  
  27.           
  28.         //初始化图中节点与源点0的最小距离  
  29.         for($i=1;$i<7;$i++)  
  30.         {  
  31.             if($this->G[0][$i]>0)  
  32.             {  
  33.                 $d[$i] = $this->G[0][$i];  
  34.             }  
  35.             else  
  36.             {  
  37.                 $d[$i] = 1000000;  
  38.             }  
  39.         }  
  40.   
  41.         // n-1次循环完成转移节点任务  
  42.         for($l=0;$l<6;$l++)  
  43.         {  
  44.             // 查找剩余节点中距离源点最近的节点v  
  45.             $current_min = 100000;  
  46.             $current_min_v = 0;  
  47.             foreach($V as $k=>$v)  
  48.             {   
  49.                 if($d[$v] < $current_min)  
  50.                 {  
  51.                     $current_min = $d[$v];  
  52.                     $current_min_v = $v;  
  53.                 }  
  54.             }  
  55.               
  56.             //从V中更新顶点到U中  
  57.             array_push($U,$current_min_v);  
  58.             array_splice($V,array_search($current_min_v,$V),1);  
  59.               
  60.             //更新  
  61.             foreach($V as $k=>$u)  
  62.             {  
  63.                 if($this->G[$current_min_v][$u]!=0&&$d[$u]>$d[$current_min_v]+$this->G[$current_min_v][$u])  
  64.                 {  
  65.                     $d[$u] = $d[$current_min_v]+$this->G[$current_min_v][$u];  
  66.                 }  
  67.             }  
  68.               
  69.         }  
  70.           
  71.         foreach($d as $k => $u)  
  72.         {  
  73.             echo $k.'=>'.$u.'<br>';  
  74.         }  
  75.           
  76.     }  
  77. }  
  78. ?>  
  1. $D = new Dijkstra;  
  2. $D->calculate(); 

猜你喜欢

转载自my.oschina.net/u/3654907/blog/1612539