Tuesday, September 25, 2018

FloydWarshall Algorithm With Path Printing

Back To Coding ...
Below code is for Finding All Pair Shortest Path Using Floyd Warshall Algorithm . Floyd Warshall Algorithm has O(n^3) time complexity and O(n^2) Space complexity .

Below code  is able to display the paths traverse between nodes .


#include<stdio.h>
#define size 4
#define INF 234334

int pathMatrix[size][size];

void pathdisplay(int pathMatrix[size][size],int u,int v);

void floydWarshall(int graph[][size]);
void display(int graph[][size]);
void main()
{

  int u,v;
  int vertex[size][size]={ {0,11,1,6},
                        {11, 0,7, 3},
                        {1, 7, 0, 2},
                        {6,3,2, 0}
                    };


  floydWarshall(vertex);

/*printf("Enter u \n");
scanf("%d",&u);
printf("Enter v \n");
scanf("%d",&v);
*/

for(u=0;u<size;u++)
{
  for(v=0;v<size;v++)
{
pathdisplay(pathMatrix,u,v);
printf("\n");
}
  printf("\n");
}
}

void floydWarshall(int vertex[size][size])
{
int graph[size][size];
int i,j,k;

for(i=0;i<size;i++)
{
  for(j=0;j<size;j++)
  {
    graph[i][j]=vertex[i][j];
    pathMatrix[i][j]=i;
  }
}


for(k=0;k<size;k++)
{
  for(i=0;i<size;i++)
  {
    for(j=0;j<size;j++)
    {
      if(graph[i][k]+graph[k][j]<graph[i][j])
      {

      graph[i][j]=graph[i][k]+graph[k][j];
      pathMatrix[i][j]=k;
    }
    }
  }
}
display(graph);
printf("\n\nPathMatrix\n");
display(pathMatrix);

}


void display(int graph[size][size])
{
int i,j;
for(i=0;i<size;i++)
{
  for(j=0;j<size;j++)
  {
   printf("%d ",graph[i][j]);
  }
  printf("\n");
}
}

void pathdisplay(int pathMatrix[size][size],int u,int v)
{
  if(u==v)
  printf("-> %d ",u);
   else if(pathMatrix[u][v]==INF)
        printf("No Path Exits\n");
     else
     {
     pathdisplay(pathMatrix,u,pathMatrix[u][v]);
      printf("-> %d ",v);
      }

}

No comments:

Post a Comment

Behavior Recognition System Based on Convolutional Neural Network

Our this article is on this  research paper .  Credit : Bo YU What we will do ? We build a set of human behavior recognition syste...