HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Warshall's algorithm for transitive closure

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
warshalltransitivealgorithmforclosure

Problem

I was going through this code for implementing Warshall's algorithm.
I think the time complexity for this simple problem is huge because there are too many loops running here. The time complexity for this code should be \$O(n^3)\$.

Is there a way to optimize this code so that the time complexity can be reduced a bit?

#include
#include
#include
int maximum(int,int);
void warshal(int p[10][10],int n)
{
int i,j,k;

for(i=1;ib)
return(a);
else
return(b);
}
void main()
{
int p[10][10]={0},n,e,u,v,i,j;

 printf("\n Enter the number of vertices:");
 scanf("%d",&n);

 printf("\n input values now\n");
 for(i=1;i<=n;i++)
  for(j=1;j<=n;j++)
   scanf("%d",&p[i][j]);

   printf("\n Matrix of input data: \n");
 for(i=1;i<=n;i++)
 {
   for(j=1;j<=n;j++)
 printf("%d\t",p[i][j]);
 printf("\n");
 }
 warshal(p,n);
 printf("\n Transitive closure: \n");
 for(i=1;i<=n;i++)
 {
 for(j=1;j<=n;j++)
 printf("%d\t",p[i][j]);
 printf("\n");
 }
  }

Solution

Arrays are 0-indexed

In C, arrays are 0-indexed. Not 1-indexed. So you're skipping the first element and running off the back in these loops. You want:

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


Use braces

Nested logic is crying for braces to make it easer to read:

for(i=0;i<n;i++) {
  for(j=0;j<n;j++) {
    for(k=0;k<n;k++) {
    }
  }
}


That'll also future proof anything else you add into these loops. What if you added logging? You'd have to go back and add braces then anyway. It's a good habit to get into. Always braces.

maximum()

There's actually no reason for this function. The logic you want is:

R(k)[i, j] = R(k-1)[i, j] or (R(k-1)[i,k] and R(k-1)[k,j])


We can just do that directly using bitwise math:

for(i=0;i<n;i++) {
  for(j=0;j<n;j++) {
    for(k=0;k<n;k++) {
      p[i][j] = p[i][j] | (p[i][k] & p[k][j]);
    }
  }
}

Code Snippets

for(i=0;i<n;i++)
  for(j=0;j<n;j++)
    for(k=0;k<n;k++)
for(i=0;i<n;i++) {
  for(j=0;j<n;j++) {
    for(k=0;k<n;k++) {
    }
  }
}
R(k)[i, j] = R(k-1)[i, j] or (R(k-1)[i,k] and R(k-1)[k,j])
for(i=0;i<n;i++) {
  for(j=0;j<n;j++) {
    for(k=0;k<n;k++) {
      p[i][j] = p[i][j] | (p[i][k] & p[k][j]);
    }
  }
}

Context

StackExchange Code Review Q#106374, answer score: 2

Revisions (0)

No revisions yet.