0% found this document useful (0 votes)
26 views

Warshall Algorithm

The Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs, but not graphs with negative cycles. The algorithm uses dynamic programming to efficiently calculate shortest paths between all pairs of vertices in O(V^3) time by iteratively updating the graph. Pseudocode and a C implementation are provided.

Uploaded by

A H M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Warshall Algorithm

The Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs, but not graphs with negative cycles. The algorithm uses dynamic programming to efficiently calculate shortest paths between all pairs of vertices in O(V^3) time by iteratively updating the graph. Pseudocode and a C implementation are provided.

Uploaded by

A H M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Warshall Algorithm:

Floyd-Warshall Algorithm is an algorithm for finding the shortest path between

all the pairs of vertices in a weighted graph. This algorithm works for both the

directed and undirected weighted graphs. But, it does not work for the graphs

with negative cycles (where the sum of the edges in a cycle is negative).This

algorithm follows the dynamic programming approach to find the shortest

paths.

CODE:

#include <stdio.h>

#include <stdlib.h>

void floydWarshall(int **graph, int n)

int i, j, k;

for (k = 0; k < n; k++)

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

{
if (graph[i][j] > graph[i][k] + graph[k][j])

graph[i][j] = graph[i][k] + graph[k][j];

int main(void)

int n, i, j;

printf("Enter the number of vertices: ");

scanf("%d", &n);

int **graph = (int **)malloc((long unsigned) n * sizeof(int *));

for (i = 0; i < n; i++)

graph[i] = (int *)malloc((long unsigned) n * sizeof(int));

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

{
if (i == j)

graph[i][j] = 0;

else

graph[i][j] = 100;

printf("Enter the edges: \n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

printf("[%d][%d]: ", i, j);

scanf("%d", &graph[i][j]);

printf("The original graph is:\n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)


{

printf("%d ", graph[i][j]);

printf("\n");

floydWarshall(graph, n);

printf("The shortest path matrix is:\n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

printf("%d ", graph[i][j]);

printf("\n");

return 0;

}
Example From Slide:

Shortest Path Algorithm:

Own Creating Example:

You might also like