Warshall's algorithm for transitive closure 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&lt;stdio.h&gt;
#include&lt;unistd.h&gt;
#include&lt;math.h&gt;
int maximum(int,int);
void warshal(int p[10][10],int n)
{
int i,j,k;

for(i=1;i&lt;=n;i++)
 for(j=1;j&lt;=n;j++)
   for(k=1;k&lt;=n;k++)
     p[i][j]=maximum(p[i][j],p[i][k]&amp;&amp;p[k][j]);
}
int maximum(int a,int b)
{                                                       ;
if(a&gt;b)
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",&amp;n);

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

   printf("\n Matrix of input data: \n");
 for(i=1;i&lt;=n;i++)
 {
   for(j=1;j&lt;=n;j++)
 printf("%d\t",p[i][j]);
 printf("\n");
 }
 warshal(p,n);
 printf("\n Transitive closure: \n");
 for(i=1;i&lt;=n;i++)
 {
 for(j=1;j&lt;=n;j++)
 printf("%d\t",p[i][j]);
 printf("\n");
 }
  }
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&lt;n;i++)
  for(j=0;j&lt;n;j++)
    for(k=0;k&lt;n;k++)


Use braces

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

for(i=0;i&lt;n;i++) {
  for(j=0;j&lt;n;j++) {
    for(k=0;k&lt;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&lt;n;i++) {
  for(j=0;j&lt;n;j++) {
    for(k=0;k&lt;n;k++) {
      p[i][j] = p[i][j] | (p[i][k] &amp; p[k][j]);
    }
  }
}