Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

OPEN SHORTEST PATH FIRST ROUTING PROTOCOL in C

  1. #include <stdio.h>
  2. #include <string.h>
  3. int main()
  4. {
  5. int count,src_router,i,j,k,w,v,min;
  6. int cost_matrix[100][100],dist[100],last[100];
  7. int flag[100];
  8. printf("\n Enter the no of routers");
  9. scanf("%d",&count);
  10. printf("\n Enter the cost matrix values:");
  11. for(i=0;i<count;i++)
  12. {
  13. for(j=0;j<count;j++)
  14. {
  15. printf("\n%d->%d:",i,j);
  16. scanf("%d",&cost_matrix[i][j]);
  17. if(cost_matrix[i][j]<0)cost_matrix[i][j]=1000;
  18. }
  19. }
  20. printf("\n Enter the source router:");
  21. scanf("%d",&src_router);
  22. for(v=0;v<count;v++)
  23. {
  24. flag[v]=0;
  25. last[v]=src_router;
  26. dist[v]=cost_matrix[src_router][v];
  27. }
  28. flag[src_router]=1;
  29. for(i=0;i<count;i++)
  30. {
  31. min=1000;
  32. for(w=0;w<count;w++)
  33. {
  34. if(!flag[w])
  35. if(dist[w]<min)
  36. {
  37. v=w;
  38. min=dist[w];
  39. }
  40. }
  41. flag[v]=1;
  42. for(w=0;w<count;w++)
  43. {
  44. if(!flag[w])
  45. if(min+cost_matrix[v][w]<dist[w])
  46. {
  47. dist[w]=min+cost_matrix[v][w];
  48. last[w]=v;
  49. }
  50. }
  51. }
  52. for(i=0;i<count;i++)
  53. {
  54. printf("\n%d==>%d:Path taken:%d",src_router,i,i);
  55. w=i;
  56. while(w!=src_router)
  57. {
  58. printf("\n<--%d",last[w]);w=last[w];
  59. }
  60. printf("\n Shortest path cost:%d",dist[i]);
  61. }
  62. }
  63.  
  64.  

Output:
Enter the no of routers3
Enter the cost matrix values:
0->0:
[exam47@cselinux ~]$ ./a.out
Enter the no of routers2
Enter the cost matrix values:
0->0:3
0->1:4
1->0:5
1->1:6
Enter the source router:1
1==>0:Path taken:0
<--1
Shortest path cost:5
1==>1:Path taken:1
Shortest path cost:6