Advertisement
rajath_pai

Distance Vector Algorithm

Mar 1st, 2021
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. //Write a program for distance vector algorithm to find suitable path for transmission.
  2.  
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. struct node {
  7.     int dist[20];
  8.     int from[20];
  9. } route[10];
  10.  
  11. int main()
  12. {
  13.     int dm[20][20], no;
  14.  
  15.     cout << "Enter no of nodes." << endl;
  16.     cin >> no;
  17.     cout << "Enter the distance matrix:" << endl;
  18.     for (int i = 0; i < no; i++) {
  19.         for (int j = 0; j < no; j++) {
  20.             cin >> dm[i][j];
  21.             dm[i][i] = 0;
  22.             route[i].dist[j] = dm[i][j];
  23.             route[i].from[j] = j;
  24.         }
  25.     }
  26.  
  27.     int flag;
  28.     do {
  29.         flag = 0;
  30.         for (int i = 0; i < no; i++) {
  31.             for (int j = 0; j < no; j++) {
  32.                 for (int k = 0; k < no; k++) {
  33.                     if ((route[i].dist[j]) > (route[i].dist[k] + route[k].dist[j])) {
  34.                         route[i].dist[j] = route[i].dist[k] + route[k].dist[j];
  35.                         route[i].from[j] = k;
  36.                         flag = 1;
  37.                     }
  38.                 }
  39.             }
  40.         }
  41.     } while (flag);
  42.  
  43.     for (int i = 0; i < no; i++) {
  44.         cout << "Router info for router: " << i + 1 << endl;
  45.         cout << "Dest\tNext Hop\tDist" << endl;
  46.         for (int j = 0; j < no; j++)
  47.             printf("%d\t%d\t\t%d\n", j+1, route[i].from[j]+1, route[i].dist[j]);
  48.     }
  49.     return 0;
  50. }
  51.  
  52. /*
  53. OUTPUT
  54.  
  55.  
  56. Enter no of nodes.
  57. 4
  58. Enter the distance matrix:
  59. 0 2 999 1
  60. 2 0 3 7
  61. 999 3 0 11
  62. 1 7 1 0
  63. Router info for router: 1
  64. Dest    Next Hop    Dist
  65. 1       1           0
  66. 2       2           2
  67. 3       4           2
  68. 4       4           1
  69. Router info for router: 2
  70. Dest    Next Hop    Dist
  71. 1       1           2
  72. 2       2           0
  73. 3       3           3
  74. 4       1           3
  75. Router info for router: 3
  76. Dest    Next Hop    Dist
  77. 1       2           5
  78. 2       2           3
  79. 3       3           0
  80. 4       1           6
  81. Router info for router: 4
  82. Dest    Next Hop    Dist
  83. 1       1           1
  84. 2       1           3
  85. 3       3           1
  86. 4       4           0
  87.  
  88. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement