迪科斯彻算法(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(); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值