DATA STRUCTURES PROGRAM • GRAPHS
Find Weighted Shortest Paths with Dijkstra's Algorithm
Learn how to find weighted shortest paths with dijkstra's algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 8 9 5 7
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <limits.h>
int main(void)
{
int graph[5][5] = {
{0,10,0,5,0}, {0,0,1,2,0}, {0,0,0,0,4},
{0,3,9,0,2}, {7,0,6,0,0}
};
int distance[5] = {0, INT_MAX, INT_MAX, INT_MAX, INT_MAX};
int used[5] = {0};
for (int step = 0; step < 5; step++) {
int vertex = -1;
for (int candidate = 0; candidate < 5; candidate++)
if (!used[candidate] && (vertex < 0 || distance[candidate] < distance[vertex])) vertex = candidate;
used[vertex] = 1;
for (int neighbour = 0; neighbour < 5; neighbour++)
if (graph[vertex][neighbour] && distance[vertex] != INT_MAX &&
distance[vertex] + graph[vertex][neighbour] < distance[neighbour])
distance[neighbour] = distance[vertex] + graph[vertex][neighbour];
}
for (int vertex = 0; vertex < 5; vertex++) printf("%d ", distance[vertex]);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 8 9 5 7
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Finalize the nearest unused vertex and relax all of its outgoing non-negative edges.
- Display the computed result.
Finalize the nearest unused vertex and relax all of its outgoing non-negative edges.
EFFICIENCY
Time and space complexity
Time complexity
O(V²)
Auxiliary space
O(V)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
