<?php
class dijistra
{
public $inf=0x7fffffff;//最开始把不同的边赋值无限大
public $MaxV=10000;//最大点数
public $N,$M;
public $froms;
public $tos;
public $ws;
public $dist=array();
public $path=array();
public $p=array();
public $map=array();
function dijkstra($s)
{
for($i=0;$i<=$this->N;$i++)//对于每个点,设置为没访问过,和设置距离
{
$this->p[$i]=false;
$this->dist[$i]=$this->map[$s][$i];
$this->path[$i]=$s;
}
/*设置出入点的参数*/
$this->dist[$s]=0;
$this->path[$s]=$s;
$this->p[$s]=true;
for($i=1;$i<=$this->N;$i++)//开始扫点
{
$min=$this->inf;
$k=0;
for($j=1;$j<=$this->N;$j++)
{
if(!$this->p[$j]&&$this->dist[$j]<$min)
{
$min=$this->dist[$j];
$k=$j;
}
}
if($k == 0)
{
print_r("bu tong <br>");
return;
}
$this->p[$k]=true;
for($j=1;$j<=$this->N;$j++)
{
if(!$this->p[$j]&&$this->map[$k][$j]!=$this->inf
&&$this->dist[$j]>$this->dist[$k]+$this->map[$k][$j])
{
$this->dist[$j]=$this->dist[$k]+$this->map[$k][$j];
$this->path[$j]=$k;
}
}
}
}
function init()
{
for($i=0;$i<=$this->N;$i++)//初始化将每两个点之间的边权先赋为无穷大
{
for($j=0;$j<=$this->N;$j++)
{
if($i==$j) $this->map[$i][$j]=0;
else $this->map[$i][$j]=$this->inf;
}
}
for($i=0;$i<$this->M;$i++)//对于给出的两点的边权,更换成边权
{
$frompre=$this->froms[$i];
$topre=$this->tos[$i];
$valuepre=$this->ws[$i];
$this->map[$frompre][$topre]
=$this->map[$topre][$frompre]
=$valuepre;
}
}
function main($N,$M,$froms,$tos,$ws)
{
$this->N=$N;
$this->M=$M;
$this->froms=$froms;
$this->tos=$tos;
$this->ws=$ws;
$this->init();//初始化
$this->dijkstra(1);
for($i=1;$i<=$this->N;$i++)
{
echo "dist[".$i."] = ".$this->dist[$i]."<br>";
}
}
}
?>
<?php
$N=4;//点的个数
$M=4;//边的个数
$froms=array('1','1','2','1');//边开始点
$tos=array('2','3','3','4');//边到达点
$ws=array('3','4','0','2');//边权
$d = new dijistra();
$d->main($N,$M,$froms,$tos,$ws);
?>
转载于:https://my.oschina.net/MrHou/blog/143896