Wednesday, 18 June 2014

BELLMAN FORD

Write a C program to implement Bellman Ford 
#include<stdio.h>
#include<conio.h>
int main()
{
    int i,j,s,adj[10][10],d[20],p[20],k,n;
    printf("\nEnter the number of vertices: ");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
      for(j=1;j<=n;j++)
      {
          printf("\nEnter the weight of edge from %d to %d: ",i,j);
          scanf("%d",&adj[i][j]);
      }
    }
    printf("enter the source node: ");
    scanf("%d",&s);
    for(i=1;i<=n;i++)
   {
     d[i]=32768;
     p[i]=0;
   }
   d[s]=0;
   for(i=1;i<n;i++)
   {
     for(j=1;j<=n;j++)
     {
        if(adj[i][j]!=0&&d[j]>d[i]+adj[i][j])
        {
          d[j]=d[i]+adj[i][j];
          p[j]=i;
        }
     }
   }
   for(i=1;i<=n;i++)
   {
     printf("\nShortest distance of %d from %d: %d",i,s,d[i]);
   }
   getch();
   return 0;
}

No comments:

Post a Comment