public static function calculaRuta($idEstacionOrigen, $idEstacionDestino) { $tramos = RedMetro::construyeGrafo(); $dijkstra = new Dijkstra($idEstacionOrigen, $tramos); $puntosCamino = $dijkstra->getCompletePathToNode($idEstacionDestino); $camino = array(); // construye tramos y transbordos for ($i = 0; $i < count($puntosCamino) - 1; $i++) { $estacionOrigen = RedMetro::buscaEstacion($puntosCamino[$i]); $estacionDestino = RedMetro::buscaEstacion($puntosCamino[$i + 1]); if ($estacionOrigen->getNombre() == $estacionDestino->getNombre()) { $puntosRuta[] = new Transbordo($estacionOrigen, $estacionDestino); } else { $direccion = $estacionOrigen->getLinea()->determinaDireccion($estacionOrigen, $estacionDestino); $puntosRuta[] = new Tramo($estacionOrigen, $estacionDestino, $direccion); } } // crea ruta y agrega tramos integrados y transbordos $ruta = new Ruta(RedMetro::obtenDistancia($puntosRuta), $dijkstra->getDistanceToNode($idEstacionDestino)); return self::construyeRuta($ruta, $puntosRuta); }
/** * @param $departure <p>Название города отправления</p> * @param $destination <p>Название города прибытия</p> * @param $map <p>Матрица городов. * На пересечении столбцов и строк - стоимость * проезда</p> * @param bool $strict <p>Режим работы: если true, то матрица городов * используется как есть. * Если false - матрица городов дополняется обратными * маршрутами со такой же стоимостью как прямой</p> * @return string Сообещние о выполнение данной функции */ public static function getCheapestRoute($departure, $destination, $map, $strict = true) { if (!Dijkstra::checkFormat($map)) { return Dijkstra::FORMAT_ERROR; } if (!$strict) { $map = Dijkstra::extendMap($map); } $vertices = Dijkstra::getAllVertices($map); if (!in_array($departure, $vertices) || !in_array($destination, $vertices)) { return sprintf(Dijkstra::FOUND_NO_WAY, $departure, $destination); } $wayPoint = []; $weight = array_fill_keys($vertices, PHP_INT_MAX); $weight[$departure] = 0; while ($weight) { $current = array_search(min($weight), $weight); if ($current == $destination) { break; } if (!empty($map[$current])) { foreach ($map[$current] as $related => $cost) { if (!empty($weight[$related]) && $weight[$current] + $cost < $weight[$related]) { $weight[$related] = $weight[$current] + $cost; $wayPoint[$related] = array('neighbor' => $current, 'cost' => $weight[$related]); } } } unset($weight[$current]); } if (!array_key_exists($destination, $wayPoint)) { return sprintf(Dijkstra::FOUND_NO_WAY, $departure, $destination); } $path = []; $current = $destination; while ($current != $departure) { $path[] = $current; $current = $wayPoint[$current]['neighbor']; } $path[] = $departure; $path = array_reverse($path); return sprintf(Dijkstra::ROUTE, $departure, $destination, implode('-->', $path), $wayPoint[$destination]['cost']); }
<?php include "Dijkstra.php"; // graph array $graph[0][0] = '1->10'; $graph[0][1] = '2->11'; $graph[0][2] = '3->40'; $graph[1][0] = '0->10'; $graph[1][1] = '2->55'; $graph[1][2] = '4->20'; $graph[2][0] = '0->11'; $graph[2][1] = '1->55'; $graph[2][2] = '1->54'; $graph[3][0] = '4->89'; $graph[3][1] = '4->89'; $graph[4][0] = '0->90'; $graph[4][1] = '3->89'; $algo = new Dijkstra(); $json = $algo->jalurTerpendek($graph, 0, 2); $array = json_decode($json, true); if ($array['status'] == 'success') { echo "Jalur terpendek : " . $array['content']; } else { echo "Error : " . $array['teks']; }
// add distance to next predecessor $u = $pi[$u]; } // stack will be empty if there is no route back if ($S->isEmpty()) { echo "No route from {$source} to {$target}\n"; } else { // add the source node and print the path in reverse (LIFO) order $S->push($source); echo "{$dist}:"; $sep = ''; foreach ($S as $v) { echo $sep, $v; $sep = '->'; } echo "\n"; } } } $graph = array('A' => array('B' => 3, 'D' => 3, 'F' => 6), 'B' => array('A' => 3, 'D' => 1, 'E' => 3), 'C' => array('E' => 2, 'F' => 3), 'D' => array('A' => 3, 'B' => 1, 'E' => 1, 'F' => 2), 'E' => array('B' => 3, 'C' => 2, 'D' => 1, 'F' => 5), 'F' => array('A' => 6, 'C' => 3, 'D' => 2, 'E' => 5)); $g = new Dijkstra($graph); $g->shortestPath('D', 'C'); // 3:D->E->C $g->shortestPath('C', 'A'); // 6:C->E->D->A $g->shortestPath('B', 'F'); // 3:B->D->F $g->shortestPath('F', 'A'); // 5:F->D->A $g->shortestPath('A', 'G'); // No route from A to G
$points = array(array(1, 3, 1), array(1, 2, 4), array(2, 3, 1), array(3, 4, 2)); $ourMap = array(); // Read in the points and push them into the map for ($i = 0, $m = count($points); $i < $m; $i++) { $x = $points[$i][0]; $y = $points[$i][1]; $c = $points[$i][2]; $ourMap[$x][$y] = $c; $ourMap[$y][$x] = $c; } // ensure that the distance from a node to itself is always zero // Purists may want to edit this bit out. for ($i = 0; $i < $matrixWidth; $i++) { for ($k = 0; $k < $matrixWidth; $k++) { if ($i == $k) { $ourMap[$i][$k] = 0; } } } // initialize the algorithm class $dijkstra = new Dijkstra($ourMap, I, $matrixWidth); $dijkstra->findShortestPath(1, 3); //to find only path from field 0 to field 13... //$fromClass = $_POST['fromClass']; //$toClass = $_POST['toClass']; //$dijkstra->findShortestPath($fromClass, $toClass); // Display the results echo '<pre>'; echo "\n\n the shortest route from class 1 to 3 is :\n"; echo $dijkstra->getResults(3); echo '</pre>';
$requestData = json_decode(file_get_contents('php://input'), true); $requestResult; $startPointID = $requestData[startPointID]; $endPointID = $requestData[endPointID]; $pointsIDbyIndexList = getPointsList(); $pointsIndexbyIDList = getPointsIndexByIDList($pointsIDbyIndexList); $startPointIndex = $pointsIndexbyIDList[$startPointID][Index]; $endPointIndex = $pointsIndexbyIDList[$endPointID][Index]; $routes = getRoutesArray(); $mapWidth = count($pointsIDbyIndexList); $timeMap = initTimeMap($routes, $pointsIndexbyIDList, $mapWidth); $distanceMap = initDistanceMap($routes, $pointsIndexbyIDList, $mapWidth); $dijkstra = new Dijkstra($distanceMap, 1000); $dijkstra->findShortestPath($startPointIndex, $endPointIndex); $resultByDistance = $dijkstra->getRoute($endPointIndex); $dijkstra = new Dijkstra($timeMap, 1000); $dijkstra->findShortestPath($startPointIndex, $endPointIndex); $resultByTime = $dijkstra->getRoute($endPointIndex); $resultByDistance = cahngeRouteindex($resultByDistance, $pointsIDbyIndexList); $resultByTime = cahngeRouteindex($resultByTime, $pointsIDbyIndexList); $requestResult[path] = true; $requestResult[routeByDistance] = $resultByDistance; $requestResult[routeByTime] = $resultByTime; echo json_encode($requestResult); function cahngeRouteindex($findRouteRes, $pointsIDbyIndexList) { $path = $findRouteRes[path]; $count = $findRouteRes[nodeCount]; for ($index = 0; $index < $count; $index++) { $pointIndex = $path[$index]; $path[$index] = $pointsIDbyIndexList[$pointIndex];
$matrixWidth = 20; // $points is an array in the following format: (router1,router2,distance-between-them) $points = array(array(0, 1, 4), array(0, 2, I), array(1, 2, 5), array(1, 3, 5), array(2, 3, 5), array(3, 4, 5), array(4, 5, 5), array(4, 5, 5), array(2, 10, 30), array(2, 11, 40), array(5, 19, 20), array(10, 11, 20), array(12, 13, 20)); $ourMap = array(); // Read in the points and push them into the map for ($i = 0, $m = count($points); $i < $m; $i++) { $x = $points[$i][0]; $y = $points[$i][1]; $c = $points[$i][2]; $ourMap[$x][$y] = $c; $ourMap[$y][$x] = $c; } // ensure that the distance from a node to itself is always zero // Purists may want to edit this bit out. for ($i = 0; $i < $matrixWidth; $i++) { for ($k = 0; $k < $matrixWidth; $k++) { if ($i == $k) { $ourMap[$i][$k] = 0; } } } // initialize the algorithm class $dijkstra = new Dijkstra($ourMap, I, $matrixWidth); // $dijkstra->findShortestPath(0,13); to find only path from field 0 to field 13... $dijkstra->findShortestPath(0); // Display the results echo '<pre>'; echo "the map looks like:\n\n"; echo $dijkstra->printMap($ourMap); echo "\n\nthe shortest paths from point 0:\n"; echo $dijkstra->getResults();