Programming Exercises - May 29, 2026
Quick Jump
| Program | File | Link |
|---|---|---|
| Exercise 1 : Floyd–Warshall Algorithm | FloyedWarshall.cpp | Open on GitHub |
Exercise 1 : Floyd–Warshall Algorithm
Algorithm
- Input the number of vertices
nand the adjacency matrixdist[n][n]where a large sentinel (e.g.,999) represents infinity/no direct edge. - For each intermediate vertex
kfrom0ton-1:- For each pair of vertices
(i, j)updatedist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]).
- For each pair of vertices
- After processing all intermediate vertices,
dist[i][j]holds the length of the shortest path fromitoj(or the sentinel if no path exists). - Print the resulting shortest-distance matrix, displaying
INFfor sentinel values.
Code
cpp
#include <stdio.h>
int main()
{
int n;
printf("Enter Number Of Vertices : ");
scanf("%d", &n);
int dist[n][n];
printf("Enter Adjacency Matrix :\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &dist[i][j]);
}
}
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
printf("\nShortest Distance Matrix :\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (dist[i][j] == 999)
printf("INF ");
else
printf("%3d ", dist[i][j]);
}
printf("\n");
}
return 0;
}Compile command
bash
g++ FloyedWarshall.cpp -o FloyedWarshall && ./FloyedWarshallCompile All Files
bash
g++ FloyedWarshall.cpp -o FloyedWarshall && ./FloyedWarshallTurbo C++ compatibility notes
c
// Change function signature
int main() -> void main()
// Change the final line
return 0; -> getch();