* @date 2017/8/23
* @license MIT
* -------------------------------------------------------------
* æè·¯åæï¼åæºæçè·¯å¾é®é¢
* -------------------------------------------------------------
* Dijkstra ç®æ³ä¸è¬ç表述é常æä¸¤ç§æ¹å¼ï¼ä¸ç§ç¨æ°¸ä¹
åä¸´æ¶æ å·æ¹å¼ï¼ä¸ç§æ¯ç¨OPEN, CLOSEè¡¨çæ¹å¼ï¼
* è¿éåéç¨æ°¸ä¹
åä¸´æ¶æ å·çæ¹å¼ã注æè¯¥ç®æ³è¦æ±å¾ä¸ä¸åå¨è´æè¾¹ã
* å æ¤ï¼å¨å
å«è´è¾¹å
¨çå¾ä¸è¦æ¾åºæçè·¯å¾ï¼å¯ä»¥ä½¿ç¨å¦ä¸ç§ç®æ³ -- è´å
æ¼-ç¦å¾·ç®æ³
*/
// +--------------------------------------------------------------------------
// | è§£é¢æ¹å¼
// +--------------------------------------------------------------------------
/**
* DijkstraQuery
*
* @uses PHPStorm
* @version 1.0
* @author Pu ShaoWei
*/
class DijkstraQuery
{
/**
* @var array
*/
protected $graph;
/**
* @var array
*/
protected $processed;
/**
* @var int
*/
protected $infinity;
/**
* @var string
*/
protected $start;
/**
* @var string
*/
protected $end;
/**
* DijkstraQuery constructor.
*
* @param array $graph
* @param $start
* @param $end
*/
public function __construct(array $graph, $start, $end)
{
$this->graph = $graph;
$this->start = $start;
$this->end = $end;
$this->processed = array ();
$this->infinity = mt_getrandmax();
}
/**
* æçè·¯å¾
*
* @return string
*/
public function calculate()
{
$costs = $this->graph[$this->start];
$costs[$this->end] = $this->infinity;
$node = $this->findLowestCostNode($costs);
while (null !== $node) {
$cost = $costs[$node];
$neighbors = $this->graph[$node] ?? array ();
foreach ($neighbors as $neighbor => $distance) {
$newCost = $cost + $distance;
if ($costs[$neighbor] > $newCost) {
$costs[$neighbor] = $newCost;
}
}
array_push($this->processed, $node);
$node = $this->findLowestCostNode($costs);
}
return 'The shortest distance forï¼' . $costs[$this->end];
}
/**
* findLowestCostNode
*
* @param $costs
* @return null
*/
protected function findLowestCostNode($costs)
{
$lowestCost = $this->infinity;
$lowestCostNode = null;
foreach ($costs as $node => $cost) {
if ($cost < $lowestCost && !in_array($node, $this->processed)) {
$lowestCost = $cost;
$lowestCostNode = $node;
}
}
return $lowestCostNode;
}
}
// +--------------------------------------------------------------------------
// | éªè¯ me --> claire
// +--------------------------------------------------------------------------
// â
$graph = array (
'me' => array (
'alice' => 6,
'bob' => 2,
),
'alice' => array (
'claire' => 1,
),
'bob' => array (
'alice' => 3,
'claire' => 5,
),
'claire' => array (// 没æä»»ä½é»å±
),
);
echo (new DijkstraQuery($graph, 'me', 'claire'))->calculate();