Shortest Path Finding - Dijkstra's Algorithm

Table of contents

1. Introduction to Dijkstra Algorithm

 2. Below, use C# and PHP to implement the sample code of Dijkstra's algorithm:

2.1 Using C# to implement the sample code of Dijkstra's algorithm (Dijkstra's algorithm)

2.2 Using PHP to implement the sample code of Dijkstra's algorithm (Dijkstra's algorithm)


1. Introduction to Dijkstra Algorithm

Dijkstra's algorithm is an algorithm for solving the single-source shortest path problem in a weighted directed graph. It starts from a node and calculates the shortest path from that node to all other nodes.

The basic idea of ​​Dijkstra's algorithm is to start from the starting point, gradually expand new nodes, and try to update the distance from the expanded nodes to the starting point through these nodes. At each expansion, select the unexpanded node that is currently closest to the starting point for expansion, and use the distance from the node to the starting point to update the distance from the expanded node to the starting point. This process is repeated until all nodes have been expanded.

In order to implement this algorithm, it is necessary to use an array to record the distance from each node to the starting point, an array to record whether each node has been expanded, and a two-dimensional array to record the weight of each edge in the graph. The time complexity of the algorithm is O(V^2), where V represents the number of nodes.

Dijkstra's algorithm can be optimized by a priority queue, reducing the time complexity to O(E log V), where E represents the number of edges. The node with the smallest distance from the starting point is stored in the priority queue, and the node with the smallest distance in the priority queue is selected for expansion each time it is expanded. This algorithm is known as Dijkstra's algorithm with priority queue implementation.

In short, Dijkstra's algorithm is an efficient and commonly used algorithm for solving the single-source shortest path problem, and is widely used in network routing, map navigation and other fields.

 2. Below, use C# and PHP to implement the sample code of Dijkstra's algorithm:

2.1 Using C# to implement the sample code of Dijkstra's algorithm (Dijkstra's algorithm)

The following is a sample code that implements Dijkstra's algorithm using C#. In this example, we use a two-dimensional array graphto represent the directed weighted graph, where graph[i][j]represents the weight of the edge from node i to node j; use a one-dimensional array distto record the shortest path length from each node to the starting point; Use a boolean array visitedto record whether each node has been visited.

using System;

class DijkstraAlgorithmDemo
{
    static void Main(string[] args)
    {
        int[][] graph = new int[][]
        {
            new int[] {0, 10, 3, int.MaxValue},
            new int[] {int.MaxValue, 0, 1, 2},
            new int[] {int.MaxValue, 4, 0, 8},
            new int[] {int.MaxValue, int.MaxValue, int.MaxValue, 0}
        };

        int startNode = 0;
        int[] dist = new int[graph.Length];
        bool[] visited = new bool[graph.Length];

        for (int i = 0; i < graph.Length; i++)
        {
            dist[i] = int.MaxValue;
            visited[i] = false;
        }

        dist[startNode] = 0;

        for (int count = 0; count < graph.Length - 1; count++)
        {
            int u = MinDistance(dist, visited);

            visited[u] = true;

            for (int v = 0; v < graph.Length; v++)
            {
                if (!visited[v] && graph[u][v] != int.MaxValue && dist[u] != int.MaxValue && dist[u] + graph[u][v] < dist[v])
                {
                    dist[v] = dist[u] + graph[u][v];
                }
            }
        }

        Console.WriteLine("The shortest path from node to starting point:");

        for (int i = 0; i < graph.Length; i++)
        {
            if (dist[i] == int.MaxValue)
            {
                Console.WriteLine($"{i} -> 起点: 不可达");
            }
            else
            {
                Console.WriteLine($"{i} -> 起点: {dist[i]}");
            }
        }
    }

    static int MinDistance(int[] dist, bool[] visited)
    {
        int minDist = int.MaxValue;
        int minIndex = -1;

        for (int v = 0; v < dist.Length; v++)
        {
            if (!visited[v] && dist[v] <= minDist)
            {
                minDist = dist[v];
                minIndex = v;
            }
        }

        return minIndex;
    }
}
 

In this sample code, we first define a two-dimensional array graphrepresenting a directed weighted graph. Then, a one-dimensional array distand a Boolean array visitedare defined to record the length of the shortest path from each node to the starting point and whether the node has been visited. Next, we initialize distthe array and visitedarray, and set the distance from the starting point to 0.

Next, we use a loop to expand each node in turn and update their distance from the origin. At each expansion, we select the unexpanded node that is currently closest to the starting point for expansion, and use the distance from the node to the starting point to update the distance from the expanded node to the starting point. When all nodes have been expanded, distthe length of the shortest path from each node to the starting point is recorded in the array.

Finally, we output the shortest path length from each node to the origin to the console.

2.2 Using PHP to implement the sample code of Dijkstra's algorithm (Dijkstra's algorithm)

The following is a sample code implementation of Dijkstra's algorithm using PHP. In this example, we use a two-dimensional array $graphto represent the directed weighted graph, where $graph[$i][$j]represents the weight of the edge from node i to node j; use a one-dimensional array $distto record the shortest path length from each node to the starting point; Use a boolean array $visitedto record whether each node has been visited.

<?php

$graph = array(
    array(0, 10, 3, INF),
    array(INF, 0, 1, 2),
    array(INF, 4, 0, 8),
    array(INF, INF, INF, 0)
);

$startNode = 0;
$dist = array();
$visited = array();

for ($i = 0; $i < count($graph); $i++) {
    $dist[$i] = INF;
    $visited[$i] = false;
}

$dist[$startNode] = 0;

for ($count = 0; $count < count($graph) - 1; $count++) {
    $u = minDistance($dist, $visited);

    $visited[$u] = true;

    for ($v = 0; $v < count($graph); $v++) {
        if (!$visited[$v] && $graph[$u][$v] != INF && $dist[$u] != INF && $dist[$u] + $graph[$u][$v] < $dist[$v]) {
            $dist[$v] = $dist[$u] + $graph[$u][$v];
        }
    }
}

echo "The shortest path from the node to the starting point:\n";

for ($i = 0; $i < count($graph); $i++) {
    if ($dist[$i] == INF) {
        echo "$i -> 起点: 不可达\n";
    } else {
        echo "$i -> 起点: {$dist[$i]}\n";
    }
}

function minDistance($dist, $visited) {
    $minDist = INF;
    $minIndex = -1;

    for ($v = 0; $v < count($dist); $v++) {
        if (!$visited[$v] && $dist[$v] <= $minDist) {
            $minDist = $dist[$v];
            $minIndex = $v;
        }
    }

    return $minIndex;
}

?>
 

In this sample code, we first define a two-dimensional array $graphrepresenting a directed weighted graph. Then, a one-dimensional array $distand a Boolean array $visitedare defined to record the length of the shortest path from each node to the starting point and whether the node has been visited. Next, we initialize $distthe array and $visitedarray, and set the distance from the starting point to 0.

Next, we use a loop to expand each node in turn and update their distance from the origin. At each expansion, we select the unexpanded node that is currently closest to the starting point for expansion, and use the distance from the node to the starting point to update the distance from the expanded node to the starting point. When all nodes have been expanded, $distthe length of the shortest path from each node to the starting point is recorded in the array.

Finally, we output the shortest path length from each node to the origin to the console.

Guess you like

Origin blog.csdn.net/beenles/article/details/121487982