DAA Week - 7 - DProgm - W&F
DAA Week - 7 - DProgm - W&F
a. Design and implement C Program to solve All-Pairs Shortest Paths problem using Floyd's
algorithm.
Definition: The Floyd algorithm is a graph analysis algorithm for finding shortest paths in a
weighted graph (with positive or negative edge weights). A single execution of the algorithm
will find the lengths (summed weights) of the shortest paths between all pairs of vertices
though it does not return details of the paths themselves. The algorithm is an example of
dynamic programming.
Algorithm:
Floyd’s Algorithm
Accept no .of vertices
Call graph function to read weighted graph // w(i,j)
Set D[ ] <- weighted graph matrix // get D{d(i,j)} for k=0
Program a):
#include<stdio.h>
#define INF 999
void main()
{
int a[10][10],n,i,j;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
floyd(a,n);
printf("\nShortest path matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
Output:
b. Design and implement C Program to find the transitive closure using Warshal's algorithm.
Definition: The Warshall algorithm is a graph analysis algorithm used to determine the
transitive closure of a directed graph or all paths in a directed graph by using the adjacency
matrix.. The algorithm is an example of Dynamic programming.
Algorithm
//Input: Adjacency matrix of digraph
//Output: R, transitive closure of digraph
Accept no .of vertices
Call graph function to read directed graph
Set R[ ] <- digraph matrix // get R {r(i,j)} for k=0
Print digraph
Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
R(i,j) = 1 if
{rij(k-1) = 1 OR
rik(k-1) = 1 and rkj(k-1) = 1}
Print R
Program b):
#include<stdio.h>
void warsh(int p[][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=p[i][j] || p[i][k] && p[k][j];
}
int main()
{
int a[10][10],n,i,j;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
warsh(a,n);
printf("\nResultant path matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
Output:
Enter the n value:4
Enter the graph data:
0100
0001
0000
1010
Resultant path matrix
1111
1111
0000
1111