šŸ›¤ļø Dijkstra's Shortest Path

🟔 IntermediateShortest Path

šŸ“‹ What is Dijkstra's Algorithm?

Dijkstra's finds the shortest path from a single source to all other vertices in a graph with non-negative edge weights. It uses a greedy approach with a priority queue (min-heap).

šŸ’» PHP Implementation

<?php
function dijkstra(array $graph, int $source): array {
    $n = count($graph);
    $dist = array_fill(0, $n, PHP_INT_MAX);
    $dist[$source] = 0;
    $visited = array_fill(0, $n, false);

    // Min-heap: [node, distance]
    $pq = new SplPriorityQueue();
    $pq->insert([$source, 0], 0); // PHP uses max-heap, negate for min

    while (!$pq->isEmpty()) {
        [$u, $d] = $pq->extract();
        $d = -$d; // Restore positive distance

        if ($visited[$u]) continue;
        $visited[$u] = true;

        foreach ($graph[$u] as [$v, $weight]) {
            if (!$visited[$v] && $dist[$u] + $weight < $dist[$v]) {
                $dist[$v] = $dist[$u] + $weight;
                $pq->insert([$v, -$dist[$v]], -$dist[$v]);
            }
        }
    }
    return $dist;
}

// Graph: node => [ [neighbor, weight], ... ]
$graph = [
    0 => [[1,4], [2,1]],
    1 => [[3,1]],
    2 => [[1,2], [3,5]],
    3 => [],
];

$dists = dijkstra($graph, 0);
print_r($dists); // [0=>0, 1=>3, 2=>1, 3=>4]

šŸ“Š Complexity

With Binary Heap O((V+E) log V)
With Array (dense graph) O(V²)
Space O(V)
āš ļø Limitation: Dijkstra does NOT work with negative edge weights. Use Bellman-Ford for that case.

šŸŽÆ Key Applications

  • GPS/Navigation systems
  • Network routing protocols (OSPF)
  • Social networks - shortest connection
  • Game AI pathfinding