Welcome to our deep dive into Dijkstra's Algorithm, a powerful tool in the world of C programming! In this lesson, we'll learn how to find the shortest path between nodes in a graph using Dijkstra's Algorithm. Let's get started!
Dijkstra's Algorithm is a popular algorithm used for finding the shortest paths between nodes in a graph. It is particularly useful in real-world applications like route planning, network analysis, and data compression.
Before diving into Dijkstra's Algorithm, let's briefly understand what a graph is. A graph is a collection of nodes (also called vertices) and edges that connect these nodes.
To follow along with this lesson, you'll need a C compiler like GCC (GNU Compiler Collection). If you don't have it installed, you can download it from the official GNU website.
Here's a simplified version of Dijkstra's Algorithm in C:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printSolution(int dist[], int n) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 0, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0;
}In the above code, we define a graph, calculate the shortest path from the source vertex (0 in this case) to all other vertices, and print the results.
Dijkstra's Algorithm has numerous practical applications, such as:
We've covered the basics of Dijkstra's Algorithm and implemented it in C. With practice, you'll be able to solve complex graph problems using this powerful tool. Happy coding! 💡