In C programming, finding the shortest path between nodes in a graph is a common and crucial problem with applications in various fields such as networking, transportation, and logistics. Shortest path algorithms are designed to find the most efficient route from a starting node to a destination node, minimizing the total travel cost, which could be in terms of distance, time, or any other metric.
In this article, we will learn about types of shortest-path algorithms and about their implementations as well.
Types of Shortest Path AlgorithmsShortest path algorithms can be categorized into two main types:
- Single Source Shortest Path Algorithms: These algorithms find the shortest paths from a single source vertex to all other vertices in the graph.
- All Pair Shortest Path Algorithms: These algorithms find the shortest paths between every pair of vertices in the graph.
Single Source Shortest Path AlgorithmsAll Pair Shortest Path AlgorithmsComparison of Shortest Path AlgorithmsThe following table compares various types of shortest path algorithms:
Algorithm
| Time Complexity
| Space Complexity
| Handles Negative Weights
|
---|
Dijkstra’s
| O(V^2) or O((V+E)log V) with min-heap
| O(V)
| No
|
---|
Bellman-Ford
| O(V+E)
| O(V)
| Yes
|
---|
A* Search
| O(E)
| O(V)
| No
|
---|
Floyd-Warshall
| O(V^3)
| O(V^2)
| Yes (if no negative cycles)
|
---|
Johnson’s
| O(V^2 log V + VE)
| O(V^2)
| Yes
|
---|
Here, V is the number of vertices and E is the number of edges in the graph.
Now let’s understand about the implementation of each of these algorithms in detail.
Implementation of Dijkstra’s Algorithm in CBelow is the implementation of Dijkstra’s Algorithm in C.
Algorithm- Create an array dist[] to store the shortest distance from the source to each vertex.
- Initialize all distances as INFINITE except the source vertex (set to 0).
- Create an array included[] to track which vertices are included in the shortest path tree.
- Implement a function findminDistance() to find the vertex with the minimum distance value from the set of vertices that are not yet included in the shortest path tree.
- Repeat the following steps V-1 times (where V is the number of vertices):
- Call findminDistance() to select the vertex ‘u’ with the minimum distance from the source, among the vertices not yet processed.
- Mark ‘u’ as included by setting included[u] = 1.
- For each adjacent vertex ‘v’ of ‘u’:
- If ‘v’ is not included in the shortest path tree and there’s an edge from ‘u’ to ‘v’:
- If the total distance from the source to ‘u’ plus the weight of the edge (u,v) is less than the current distance to ‘v’, update the distance of’v’.
- After the loop completes, the dist[] array will contain the shortest distances from the source to all vertices.
- Print the final dist[] array to show the shortest distance from the source to each vertex in the graph .
C Program for Dijkstra’s AlgorithmThe following program denotes the implementation of shortest path algorithm in C:
C
// C Program to Implement Shortest Path Algorithm
#include <limits.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 5
// Function to find the vertex with the minimum distance
// value from the set of vertices not yet included in the
// shortest path tree
int findminDistance(int dist[], int included[])
{
int min = INT_MAX, min_index;
// Traverse all vertices to find the vertex with the
// minimum distance value
for (int v = 0; v < V; v++) {
if (included[v] == 0 && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
// Function to print the constructed distance array
void printSolution(int dist[])
{
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
// Function that implements Dijkstra's algorithm
void DijkstrasAlgo(int graph[V][V], int src)
{
// Array to store the minimum distance from source node
// to the current node
int dist[V];
// Array to keep track of included nodes
int included[V];
// Initialize all distances as INFINITE and included as
// false
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
included[i] = 0;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find the shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// vertices not yet processed
int u = findminDistance(dist, included);
// Mark the selected vertex as included
included[u] = 1;
// Update the distance of all the adjacent vertices
// of the selected vertex
for (int v = 0; v < V; v++) {
// update dist[v] if it is already note included
// and the current distance is less then it's
// original distance
if (!included[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
// Print the constructed distance array
printSolution(dist);
}
int main()
{
int graph[V][V] = {
{ 0, 1, 4, 6, 1 }, // Node A (0) connections
{ 1, 0, 0, 2, 0 }, // Node B (1) connections
{ 4, 0, 0, 0, 1 }, // Node C (2) connections
{ 6, 2, 0, 0, 5 }, // Node D (3) connections
{ 1, 0, 1, 5, 0 } // Node E (4) connections
};
// Perform Dijkstra's algorithm starting from vertex 0
// (Node A)
DijkstrasAlgo(graph, 0);
return 0;
}
OutputVertex Distance from Source
0 0
1 1
2 2
3 3
4 1
Note: The Dijksta’s algorithm works fine for graphs having positive weights but it fails for graphs having negative weights. To find the shortest path for graphs having negative weights you can refer to this article : Bellman Ford Algorithm
Implementation of Bellman Ford Algorithm in CBelow is the implementation of Bellman Ford Algorithm in C.
Algorithm- Create an array dist[] to store the shortest distance from the source to each vertex.
- Initialize all distances as INFINITE except the source vertex (set to 0).
- Repeat the following steps V-1 times (where V is the number of vertices):
- For each edge (u, v) with weight w in the graph:
- If dist[u] + w < dist[v], then update dist[v] = dist[u] + w.
- For each edge (u, v) with weight w in the graph:
- If dist[u] + w < dist[v], then the graph contains a negative weight cycle.
- If no negative weight cycle is detected, print the final dist[] array.
C Program for Bellman Ford AlgorithmThe following program denotes the implementation of Bellman Ford algorithm in C:
C
// C program for Bellman Ford algorithm
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// Structure to represent an edge in the graph
struct Edge {
int src, dest, weight;
};
// Structure to represent a graph
struct Graph {
// V: Number of vertices, E: Number of edges
int V, E;
// Array of edges
struct Edge* edge;
};
// Function to create a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph
= (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->E = E;
graph->edge = (struct Edge*)malloc(
graph->E * sizeof(struct Edge));
return graph;
}
// Function to run Bellman-Ford algorithm from a source
// vertex src
void BellmanFord(struct Graph* graph, int src)
{
// Number of vertices in the graph
int V = graph->V;
// Number of edges in the graph
int E = graph->E;
// Array to hold the shortest distance from src to each
// vertex
int dist[V];
// Step 1: Initialize distances from src to all other
// vertices as INFINITE
for (int i = 0; i < V; i++)
dist[i] = INT_MAX;
dist[src] = 0;
// Step 2: Relax all edges |V| - 1 times.
// A simple shortest path from src to any other vertex
// can have at most |V| - 1 edges
for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph->edge[j].src;
int v = graph->edge[j].dest;
int weight = graph->edge[j].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
// Step 3: Check for negative-weight cycles.
// The above step guarantees shortest distances if the
// graph doesn't contain negative weight cycles. If we
// get a shorter path, then there is a cycle.
for (int i = 0; i < E; i++) {
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
int weight = graph->edge[i].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v]) {
printf("Graph contains negative weight cycle");
// If negative weight cycle is detected, return
return;
}
}
// Print the calculated shortest distances
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
// Main function to run the Bellman-Ford algorithm
int main()
{
// Number of vertices
int V = 5;
// Number of edges
int E = 8;
struct Graph* graph = createGraph(V, E);
// Adding edges to the graph
// Edge 0-1
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
// Edge 0-2
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
// Edge 1-2
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
// Edge 1-3
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
// Edge 1-4
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
// Edge 3-2
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
// Edge 3-1
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
// Edge 4-3
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
// Run Bellman-Ford algorithm from vertex 0
BellmanFord(graph, 0);
return 0;
}
OutputVertex Distance from Source
0 0
1 -1
2 2
3 -2
4 1
Implementation of A* Search Algorithm in CBelow is the implementation of A* Search Algorithm in C.
Algorithm- openSet contains nodes to be evaluated.
- closedSet contains nodes already evaluated.
- Create two lists: openSet and closedSet.
- Add the starting node to openSet.
- While openSet is not empty:
- Find the node in openSet with the lowest f_score (current).
- If current is the goal, return the path.
- Remove current from openSet and add it to closedSet.
- For each neighbor of current:
- If neighbor is in closedSet, skip it.
- If neighbor is not in openSet:
- Calculate tentative g_score for neighbor.
- If tentative g_score is worse than the existing g_score, skip.
- Update neighbor’s g_score, h_score, and f_score:
- g_score = cost from start to neighbor
- h_score = estimated cost from neighbor to goal (heuristic)
- f_score = g_score + h_score
- Set neighbor’s parent to current.
- If openSet is empty and goal not reached, return failure (no path exists).
- Reconstruct and return the path from start to goal using parent pointers.
C Program for A* Search AlgorithmThe following program denotes the implementation of A* Search Algorithm in C:
C
// C Program for A* Search Algorithm
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 1000
#define MAX_SUCCESSORS 8
// Structure to represent a point in the grid
typedef struct {
int x, y;
} Point;
// Structure to represent a node in the search tree
typedef struct Node {
// Position of the node in the grid
Point pos;
// Cost from the start node to this node
int g;
// Heuristic cost from this node to the goal node
int h;
// Total cost (g + h)
int f;
// Pointer to the parent node
struct Node* parent;
} Node;
// Structure to represent a list of nodes (either open or
// closed)
typedef struct {
// Array of node pointers
Node* nodes[MAX_NODES];
// Current size of the list
int size;
} List;
// Function to create a new node
Node* createNode(Point pos, Node* parent, int g, int h)
{
Node* node = (Node*)malloc(sizeof(Node));
node->pos = pos;
node->parent = parent;
node->g = g;
node->h = h;
node->f = g + h;
return node;
}
// Function to add a node to a list
void addToList(List* list, Node* node)
{
list->nodes[list->size++] = node;
}
// Function to get the node with the lowest 'f' value from a
// list
Node* getLowestF(List* list)
{
int lowestIndex = 0;
for (int i = 1; i < list->size; i++) {
if (list->nodes[i]->f
< list->nodes[lowestIndex]->f) {
lowestIndex = i;
}
}
Node* node = list->nodes[lowestIndex];
list->nodes[lowestIndex] = list->nodes[--list->size];
return node;
}
// Function to check if a point is in a list
bool isInList(List* list, Point pos)
{
for (int i = 0; i < list->size; i++) {
if (list->nodes[i]->pos.x == pos.x
&& list->nodes[i]->pos.y == pos.y) {
return true;
}
}
return false;
}
// Heuristic function (Manhattan distance)
int heuristic(Point a, Point b)
{
return abs(a.x - b.x) + abs(a.y - b.y);
}
// A* Search Algorithm implementation
Point* aStar(int grid[10][10], Point start, Point goal)
{
// List of nodes to be evaluated
List openList = { 0 };
// List of nodes already evaluated
List closedList = { 0 };
// Add the start node to the open list
addToList(
&openList,
createNode(start, NULL, 0, heuristic(start, goal)));
// Main loop
while (openList.size > 0) {
// Get the node with the lowest 'f' value
Node* current = getLowestF(&openList);
// Check if the goal is reached
if (current->pos.x == goal.x
&& current->pos.y == goal.y) {
// Path found, reconstruct and return
int pathLength = 0;
Node* pathNode = current;
while (pathNode) {
pathLength++;
pathNode = pathNode->parent;
}
Point* path = (Point*)malloc(pathLength
* sizeof(Point));
pathNode = current;
for (int i = pathLength - 1; i >= 0; i--) {
path[i] = pathNode->pos;
pathNode = pathNode->parent;
}
// Return the found path
return path;
}
// Move the current node to the closed list
addToList(&closedList, current);
// Generate successors (8 possible movements)
Point successors[MAX_SUCCESSORS]
= { { current->pos.x + 1, current->pos.y },
{ current->pos.x - 1, current->pos.y },
{ current->pos.x, current->pos.y + 1 },
{ current->pos.x, current->pos.y - 1 },
{ current->pos.x + 1, current->pos.y + 1 },
{ current->pos.x + 1, current->pos.y - 1 },
{ current->pos.x - 1, current->pos.y + 1 },
{ current->pos.x - 1,
current->pos.y - 1 } };
// Evaluate each successor
for (int i = 0; i < MAX_SUCCESSORS; i++) {
Point successor = successors[i];
// Check if the successor is within the grid and
// not an obstacle
if (successor.x < 0 || successor.x >= 10
|| successor.y < 0 || successor.y >= 10
|| grid[successor.x][successor.y] == 1
|| isInList(&closedList, successor)) {
continue;
}
// Increment the cost
int newG = current->g + 1;
// Calculate the heuristic
int newH = heuristic(successor, goal);
// Calculate the total cost
int newF = newG + newH;
// Check if this path is better than any
// previously found path
if (!isInList(&openList, successor)
|| newF < current->f) {
addToList(
&openList,
createNode(successor, current, newG,
newH)); // Add to open list
}
}
}
// No path found
return NULL;
}
int main()
{
// Grid with obstacles
int grid[10][10] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
// Start point
Point start = { 0, 0 };
// Goal point
Point goal = { 9, 9 };
// Run A* algorithm
Point* path = aStar(grid, start, goal);
// Print the result
if (path) {
printf("Path found:\n");
for (int i = 0;
path[i].x != goal.x || path[i].y != goal.y;
i++) {
printf("(%d,%d) -> ", path[i].x, path[i].y);
}
printf("(%d,%d)\n", goal.x, goal.y);
// Free allocated memory for the path
free(path);
}
else {
printf("No path found.\n");
}
return 0;
}
OutputPath found:
(0,0) -> (1,1) -> (2,2) -> (3,3) -> (4,3) -> (5,3) -> (6,3) -> (7,3) -> (8,3) -> (9,4) -> (9,5) -> (9,6) -> (9,7) -> (9,8) -> (9,9)
Implementation of Floyd-Warshall Algorithm in CBelow is a implementation of Floyd-Warshall Algorithm in C.
Algorithm- Create a 2D array dist[][] to store the shortest distances between every pair of vertices.
- Initialize the dist[][] array with the direct edge weights from the input graph.
- For vertices with no direct edge, set the distance to INFINITY.
- Set the distance from a vertex to itself as 0.
- For each vertex k as an intermediate vertex:
- For each pair of vertices (i, j):
- If dist[i][k] + dist[k][j] < dist[i][j], update dist[i][j] = dist[i][k] + dist[k][j].
- After the loops complete, dist[][] will contain the shortest distances between all pairs of vertices.
- Print the final dist[][] array.
C Program for Floyd-Warshall AlgorithmThe following program denotes the implementation of Floyd-Warshall Algorithm in C:
C
// C Program for Floyd-Warshall Algorithm
#include <limits.h>
#include <stdio.h>
// Number of vertices in the graph
#define V 4
#define INF INT_MAX
// Function to print the solution matrix
void printSolution(int dist[][V])
{
printf("Shortest distances between every pair of "
"vertices:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}
// Function to implement the Floyd-Warshall algorithm
void floydWarshall(int graph[][V])
{
int dist[V][V];
// Initialize the solution matrix same as the input
// graph matrix.
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];
// Add all vertices one by one to the set of
// intermediate vertices.
for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above-picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from
// i to j, then update the value of
// dist[i][j]
if (dist[i][k] != INF && dist[k][j] != INF
&& dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
}
int main()
{
// Define a graph with V vertices
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
// Perform Floyd-Warshall algorithm to find all pairs
// shortest paths
floydWarshall(graph);
return 0;
}
OutputShortest distances between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0
Implementation of Johnson’s Algorithm in CBelow is the implementation of Johnson’s Algorithm in C.
Algorithm- Create a new vertex q and add edges with weight 0 from q to all other vertices.
- Run Bellman-Ford algorithm with q as source to check for negative weight cycles and to get h[v] for each vertex v.
- If Bellman-Ford detects a negative weight cycle, stop.
- For each edge (u, v) with weight w(u, v), set its new weight to: w(u, v) + h[u] – h[v].
- Remove vertex q and its edges.
- For each vertex u:
- Run Dijkstra’s algorithm with u as the source on the reweighted graph.
- For each vertex v, set dist[u][v] = dist'[u][v] + h[v] – h[u], where dist'[u][v] is the distance in the reweighted graph.
- Return the dist[][] array containing shortest distances between all pairs of vertices.
C Program for Johnson’s AlgorithmThe following program denotes the implementation of Johnson’s Algorithm in C:
C
// C Program for Johnson's Algorithm
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// Maximum number of vertices
#define MAX_V 5
#define INF INT_MAX
// Structure to represent an edge
struct Edge {
int src, dest, weight;
};
// Structure to represent a graph
struct Graph {
int V, E;
struct Edge* edge;
};
// Function to create a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
struct Graph* graph
= (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->E = E;
graph->edge
= (struct Edge*)malloc(E * sizeof(struct Edge));
return graph;
}
// Function to perform Bellman-Ford algorithm
void bellmanFord(struct Graph* graph, int src, int dist[])
{
int V = graph->V;
int E = graph->E;
// Initialize distances from src to all other vertices
// as INFINITE
for (int i = 0; i < V; i++)
dist[i] = INF;
dist[src] = 0;
// Relax all edges |V| - 1 times
for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph->edge[j].src;
int v = graph->edge[j].dest;
int weight = graph->edge[j].weight;
if (dist[u] != INF
&& dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
}
// Function to find the vertex with the minimum distance
// value
int minDistance(int dist[], int sptSet[], int V)
{
int min = INF, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == 0 && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
// Function to perform Dijkstra's algorithm
void dijkstra(int graph[MAX_V][MAX_V], int src, int dist[],
int V)
{
int sptSet[MAX_V];
// Initialize distances from src to all other vertices
// as INFINITE and sptSet[] as false
for (int i = 0; i < V; i++)
dist[i] = INF, sptSet[i] = 0;
dist[src] = 0;
// Find shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet, V);
sptSet[u] = 1;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] != INF
&& dist[u] != INF
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
}
// Function to perform Johnson's algorithm
void johnson(struct Graph* graph)
{
int V = graph->V;
// Create a new graph with an extra vertex
struct Graph* g = createGraph(V + 1, graph->E + V);
// Copy all edges from the original graph to the new
// graph
int i;
for (i = 0; i < graph->E; i++) {
g->edge[i] = graph->edge[i];
}
// Add edges from the new vertex to all other vertices
// with weight 0
for (int j = 0; j < V; j++, i++) {
g->edge[i].src = V;
g->edge[i].dest = j;
g->edge[i].weight = 0;
}
// Run Bellman-Ford to find shortest paths from the new
// vertex
int dist[MAX_V + 1];
bellmanFord(g, V, dist);
// Reweight the edges of the original graph
int reweighted[MAX_V][MAX_V];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
reweighted[i][j] = (i == j) ? 0 : INF;
}
}
for (int i = 0; i < graph->E; i++) {
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
reweighted[u][v]
= graph->edge[i].weight + dist[u] - dist[v];
}
// Run Dijkstra's algorithm for each vertex
printf("Shortest distances between every pair of "
"vertices:\n");
for (int src = 0; src < V; src++) {
int shortestDist[MAX_V];
dijkstra(reweighted, src, shortestDist, V);
for (int i = 0; i < V; i++) {
if (shortestDist[i] == INF) {
printf("%7s", "INF");
}
else {
int distance
= shortestDist[i] + dist[i] - dist[src];
printf("%7d", distance);
}
}
printf("\n");
}
}
int main()
{
int V = 4, E = 5;
struct Graph* graph = createGraph(V, E);
// Add edges to the graph
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 1;
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 2;
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 5;
graph->edge[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight = 1;
// Perform Johnson's algorithm to find all pairs
// shortest paths
johnson(graph);
return 0;
}
OutputShortest distances between every pair of vertices:
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF INF 0
Applications of Shortest Path AlgorithmsFollowing are some the common applications of shortest path algorithms:
- GPS and Navigation Systems: Finding the shortest or fastest route between two locations.
- Network Routing Protocols: Determining the most efficient path for data packets in computer networks.
- Social Networks: Finding the shortest connection between two people.
- AI and Robotics: Path planning for autonomous vehicles or robots.
- Transportation and Logistics: Optimizing delivery routes or public transportation systems.
|