DATA STRUCTURES PROGRAM • GRAPHS
Find All-Pairs Shortest Paths with Floyd-Warshall
Learn how to find all-pairs shortest paths with floyd-warshall using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 to 3 = 9 1 to 3 = 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int distance[4][4] = {
{0,5,999,10}, {999,0,3,999}, {999,999,0,1}, {999,999,999,0}
};
for (int through = 0; through < 4; through++)
for (int from = 0; from < 4; from++)
for (int to = 0; to < 4; to++)
if (distance[from][through] + distance[through][to] < distance[from][to])
distance[from][to] = distance[from][through] + distance[through][to];
printf("0 to 3 = %d\n", distance[0][3]);
printf("1 to 3 = %d\n", distance[1][3]);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 to 3 = 9 1 to 3 = 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Allow each vertex in turn as an intermediate point for every source-destination pair.
- Display the computed result.
Allow each vertex in turn as an intermediate point for every source-destination pair.
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.
