Distance Vector Routing (DVR) Algorithm in C++: Bellman-Ford Walkthrough and Count-to-Infinity
Distance vector routing in C++, built from scratch: the one Bellman-Ford rule every router applies, round-by-round routing tables, and what happens when a link breaks (count-to-infinity and poison reverse), all compiled and run.
Imagine a router in a network of fifty. It can see the links that touch it — a few neighbours, each with a cost — and nothing else. No map, no list of the other forty-odd routers. Yet when a packet for some distant destination arrives, it must pick the right neighbour to hand the packet to. Distance Vector Routing (DVR) is the oldest answer to that problem, and a surprisingly simple one: every router keeps a small table of “how far is each destination, and which neighbour do I send to”, and every so often it tells its neighbours what is in that table. Listening to neighbours is enough for the whole network to settle on correct shortest paths.
This post builds DVR from nothing, in C++, and runs it. You will see the table each router starts with, the single rule that updates it, a full walk-through of the rounds by hand, and then the part most textbooks rush past: what happens when a link breaks and the routers start counting to infinity. It replaces two earlier posts on this site about the same program; both had problems, and the section near the end shows exactly what they were.
Versions and verification. Everything below was compiled with g++ 13.3.0 (Ubuntu 24.04) using -std=c++17 and run on 12 November 2026. Every table and transcript in the post is quoted from a file in the companion code, regenerated by one script, run-all.sh. The simulator also checks each converged result against an independent Floyd-Warshall computation and prints match or MISMATCH.
Every router starts knowing only its own links
Take four routers wired in a square. The numbers on the links are costs — hop count, delay, whatever the network cares about. Router A is attached to B (cost 1) and D (cost 4), and that is all A knows.
The table in the picture is the whole data structure of DVR. One row per destination, three columns: the destination, the distance A currently believes it has to it, and the next hop — the neighbour A will hand a packet to. A knows its own distance to itself is 0. For C there is no link and no information, so the distance is infinity. The simulator prints exactly this at round 0 (01-four-node-trace.txt):
A Routing Table
Dest Dist Next hop
A 0 -
B 1 B
C INF -
D 4 D
The input that produced it is four lines in four-node.txt: the number of routers, then the cost of every possible link in the order A-B, A-C, A-D, B-C and so on, with -1 meaning “no link”.
Going deeper: what “distance” and “infinity” mean in practice
A “cost” is whatever metric the protocol uses. The classic distance-vector protocol, RIP, counts hops: every link costs 1. Real protocols also need a finite stand-in for infinity, because a table cannot hold a true infinity and the algorithm needs a ceiling to stop at. RIP picks 16, which is why a RIP network cannot be more than 15 hops across (RFC 2453, sections 3.2 and 3.4.2). The simulator uses the same value by default and takes --infinity N if you want to experiment. You will see in the failure section why the ceiling is not a detail.
One rule does all the work: ask the neighbours, add the link cost, keep the smallest
Routers update their tables by listening. In each round, every router reads the tables its neighbours had at the end of the previous round and, for each destination, asks one question: which neighbour gives me the cheapest total? The total is the cost of the link to that neighbour plus the distance the neighbour claims to have. Written as a formula, this is the Bellman-Ford equation, and it is the only formula in the whole algorithm:
D(x, y) = min over neighbours v of [ cost(x, v) + D(v, y) ]
Read it as “my distance to y is the best of: the cost to reach a neighbour, plus that neighbour’s own distance to y”. The neighbour that wins becomes the next hop. Here is router B working out its route to D in round 1.
B is not connected to D, so it cannot know the answer alone. It asks A and C. A reports 4, C reports 3. B adds the link costs it knows (1 to reach A, 2 to reach C) and gets 5 either way. The picture contains the whole idea: no router ever sees more than its neighbours’ tables, and that is enough. The program breaks the tie in favour of the lower-lettered neighbour (A) and keeps the current choice on later ties so routes do not flip back and forth.
After one round the four-node network is already finished. These are the tables for A and B after round 1, quoted from the same transcript (01-four-node-trace.txt):
A Routing Table
Dest Dist Next hop
A 0 -
B 1 B
C 3 B
D 4 D
B Routing Table
Dest Dist Next hop
A 1 A
B 0 -
C 2 C
D 5 A
Check A→C by hand: through B costs 1 + 2 = 3, through D costs 4 + 3 = 7, so 3 via B — and the table says C 3 B. B→D is the tie from the diagram, 5 via A. The program then runs a second round, sees that nothing changed, and stops (the last lines of the same file):
converged: round 2 changed nothing
rounds that changed something: 1
check vs Floyd-Warshall: match
Why one round was enough here. After round k every router knows the best route that uses at most k+1 links, because round 0 already holds one-link routes and each round extends every route by one more link. The longest best path in this network is two links, so one round was enough. A five-router chain whose longest best path is four links needs three rounds; the simulator says so in 07-chain-five-dvr.txt.
Intermediate: a second walk-through, where information needs two rounds to arrive
The earlier version of this post used a five-router network (links A-B=5, A-C=2, A-D=3, B-C=4, B-E=3, C-E=4, in five-node.txt). It is a better teaching example because D and E are not neighbours and the news about D has to travel. After round 1, E has no route to D at all:
E Routing Table
Dest Dist Next hop
A 6 C
B 3 B
C 4 C
D INF -
E’s neighbours are B and C, and at round 0 neither knew a route to D, so E had nothing to add to. But in round 1 C learned that D is 5 away via A. In round 2 E can now use C’s fresh number: 4 (the link E-C) + 5 = 9, which beats B’s 3 + 8 = 11:
E Routing Table
Dest Dist Next hop
A 6 C
B 3 B
C 4 C
D 9 C
This is the answer the 2015 post printed (“D 9”), and also its famous A→E result: A reaches E in 6 via C (2 + 4), cheaper than via B (5 + 3 = 8). The full transcript, with every router after every round, is 02-five-node-trace.txt.
The routes reach farther by one link per round, which is why DVR on a big network takes time proportional to its diameter.
Real routers are not synchronised: each sends its table on a timer (every 30 seconds for RIP, RFC 2453 section 3.8) or when something changes, so convergence takes seconds to minutes rather than rounds.
The whole program is one function that applies that rule
The simulator is a single file, dvr.cpp. The routing logic is the function below. For every router x and every destination y it tries every neighbour v, takes the neighbour’s distance from snapDist (the snapshot of the previous round, so all routers update “at the same time”), adds the link cost and keeps the best. Anything at or above INF is treated as unreachable.
// One synchronous round. Returns true if any entry changed.
static bool exchangeRound(Network& g) {
const auto snapDist = g.dist; // what neighbours advertised at the end of the last round
const auto snapNext = g.next;
bool changed = false;
for (int x = 0; x < g.n; x++) {
for (int y = 0; y < g.n; y++) {
if (x == y) continue;
int best = INF, hop = -1;
for (int v = 0; v < g.n; v++) {
if (v == x || g.cost[x][v] < 0) continue; // v must be a neighbour
int advertised = snapDist[v][y];
if (poison && snapNext[v][y] == x) advertised = INF; // poison reverse
int cand = min(INF, g.cost[x][v] + advertised);
// strict '<' keeps the lowest-lettered neighbour on a tie, unless the
// current next hop ties, in which case we keep it (avoids route flapping)
if (cand < best || (cand == best && cand < INF && v == snapNext[x][y])) { best = cand; hop = v; }
}
if (best != g.dist[x][y] || hop != g.next[x][y]) changed = true;
g.dist[x][y] = best;
g.next[x][y] = (best >= INF) ? -1 : hop;
}
}
return changed;
}
Build and run it with the commands below (the same ones run-all.sh uses). Add --trace to see every router’s table after every round, or --watch C to follow just one destination, which is what the next section uses.
Reference: the full program (207 lines), with the input format
The input is whitespace-separated numbers with # comments. After the link costs you may add fail X Y or cost X Y c lines; each one changes the network and runs the simulation again until it settles. That is how the next section breaks a link. File: dvr.cpp.
// dvr.cpp - Distance Vector Routing (DVR) simulator.
//
// Every router keeps ONE table: for each destination, (distance, next hop).
// Time moves in synchronous rounds. In each round every router reads the
// tables its neighbours had at the END of the previous round and applies the
// Bellman-Ford equation
//
// D_x(y) = min over neighbours v of [ c(x,v) + D_v(y) ]
//
// The next hop for y is the neighbour v that gave the minimum. The simulation
// stops when a whole round changes nothing: that is convergence.
//
// Build: g++ -std=c++17 -Wall -Wextra -O2 -o build/dvr dvr.cpp
// Run: build/dvr [--trace] [--watch X] [--poison] [--infinity N] < input/four-node.txt
//
// Input (whitespace separated, '#' starts a comment):
// n number of routers, named A, B, C, ...
// n*(n-1)/2 numbers link costs in the order A-B, A-C, ..., B-C, B-D, ...; -1 = no link
// fail X Y (optional, repeatable) remove link X-Y, then re-converge
// cost X Y c (optional, repeatable) change link X-Y to cost c, then re-converge
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
static int INF = 16; // RIP-style "infinity": a distance >= INF means unreachable
static bool trace = false; // print every router's full table after every round
static bool poison = false; // split horizon with poison reverse
static int watchDest = -1; // print one column (distance to this router) every round
struct Network {
int n = 0;
vector<vector<int>> cost; // cost[x][y] = direct link cost, -1 = no link, 0 on the diagonal
vector<vector<int>> dist; // dist[x][y] = router x's current estimate to y
vector<vector<int>> next; // next[x][y] = neighbour x forwards to for y, -1 = none/self
};
static char name(int i) { return static_cast<char>('A' + i); }
static void initTables(Network& g) {
g.dist.assign(g.n, vector<int>(g.n, INF));
g.next.assign(g.n, vector<int>(g.n, -1));
for (int x = 0; x < g.n; x++) {
g.dist[x][x] = 0;
for (int y = 0; y < g.n; y++)
if (x != y && g.cost[x][y] >= 0) {
g.dist[x][y] = min(g.cost[x][y], INF);
g.next[x][y] = y;
}
}
}
static void printTable(const Network& g, int x) {
cout << name(x) << " Routing Table\n";
cout << "Dest Dist Next hop\n";
for (int y = 0; y < g.n; y++) {
cout << name(y) << " ";
if (g.dist[x][y] >= INF) cout << left << setw(6) << "INF" << "-\n";
else {
cout << left << setw(6) << g.dist[x][y];
cout << (g.next[x][y] < 0 ? '-' : name(g.next[x][y])) << "\n";
}
}
}
static void printAll(const Network& g) {
for (int x = 0; x < g.n; x++) { printTable(g, x); if (x + 1 < g.n) cout << "\n"; }
}
static void printWatch(const Network& g, int round) {
cout << "round " << setw(2) << right << round << " | to " << name(watchDest) << ":";
for (int x = 0; x < g.n; x++) {
if (x == watchDest) continue;
cout << " " << name(x) << "=";
if (g.dist[x][watchDest] >= INF) cout << "INF";
else cout << g.dist[x][watchDest] << "(" << name(g.next[x][watchDest]) << ")";
}
cout << "\n";
}
// One synchronous round. Returns true if any entry changed.
static bool exchangeRound(Network& g) {
const auto snapDist = g.dist; // what neighbours advertised at the end of the last round
const auto snapNext = g.next;
bool changed = false;
for (int x = 0; x < g.n; x++) {
for (int y = 0; y < g.n; y++) {
if (x == y) continue;
int best = INF, hop = -1;
for (int v = 0; v < g.n; v++) {
if (v == x || g.cost[x][v] < 0) continue; // v must be a neighbour
int advertised = snapDist[v][y];
if (poison && snapNext[v][y] == x) advertised = INF; // poison reverse
int cand = min(INF, g.cost[x][v] + advertised);
// strict '<' keeps the lowest-lettered neighbour on a tie, unless the
// current next hop ties, in which case we keep it (avoids route flapping)
if (cand < best || (cand == best && cand < INF && v == snapNext[x][y])) { best = cand; hop = v; }
}
if (best != g.dist[x][y] || hop != g.next[x][y]) changed = true;
g.dist[x][y] = best;
g.next[x][y] = (best >= INF) ? -1 : hop;
}
}
return changed;
}
// Independent check: Floyd-Warshall on the current links, with the same INF cap.
static bool matchesFloydWarshall(const Network& g) {
vector<vector<int>> d(g.n, vector<int>(g.n, INF));
for (int x = 0; x < g.n; x++)
for (int y = 0; y < g.n; y++)
d[x][y] = (x == y) ? 0 : (g.cost[x][y] >= 0 ? min(g.cost[x][y], INF) : INF);
for (int k = 0; k < g.n; k++)
for (int i = 0; i < g.n; i++)
for (int j = 0; j < g.n; j++)
d[i][j] = min(d[i][j], min(INF, d[i][k] + d[k][j]));
for (int x = 0; x < g.n; x++)
for (int y = 0; y < g.n; y++)
if (d[x][y] != g.dist[x][y]) return false;
return true;
}
static void converge(Network& g, const string& label) {
cout << "== " << label << " ==\n";
if (trace) { cout << "\n-- round 0 (direct links only) --\n"; printAll(g); cout << "\n"; }
if (watchDest >= 0) printWatch(g, 0);
int r = 0;
const int maxRounds = 200;
while (r < maxRounds) {
bool changed = exchangeRound(g);
if (!changed) break;
r++;
if (trace) { cout << "-- after round " << r << " --\n"; printAll(g); cout << "\n"; }
if (watchDest >= 0) printWatch(g, r);
}
cout << (r >= maxRounds ? "stopped at the round limit\n" : "converged: round " + to_string(r + 1) + " changed nothing\n");
cout << "rounds that changed something: " << r << "\n";
cout << "check vs Floyd-Warshall: " << (matchesFloydWarshall(g) ? "match" : "MISMATCH") << "\n";
if (!trace) { cout << "\n"; printAll(g); }
}
static int routerIndex(const string& s, int n) {
if (s.size() != 1 || s[0] < 'A' || s[0] >= 'A' + n) { cerr << "bad router name: " << s << "\n"; exit(2); }
return s[0] - 'A';
}
int main(int argc, char** argv) {
for (int i = 1; i < argc; i++) {
string a = argv[i];
if (a == "--trace") trace = true;
else if (a == "--poison") poison = true;
else if (a == "--infinity" && i + 1 < argc) INF = atoi(argv[++i]);
else if (a == "--watch" && i + 1 < argc) watchDest = argv[++i][0] - 'A';
else { cerr << "usage: dvr [--trace] [--watch X] [--poison] [--infinity N] < input\n"; return 2; }
}
// read all of stdin, dropping '#' comments
string all, line;
while (getline(cin, line)) { all += line.substr(0, line.find('#')); all += '\n'; }
istringstream in(all);
Network g;
if (!(in >> g.n) || g.n < 2 || g.n > 26) { cerr << "need 2..26 routers\n"; return 2; }
if (watchDest >= g.n) { cerr << "--watch router is outside the network\n"; return 2; }
g.cost.assign(g.n, vector<int>(g.n, -1));
for (int x = 0; x < g.n; x++) g.cost[x][x] = 0;
for (int x = 0; x < g.n; x++)
for (int y = x + 1; y < g.n; y++) {
int c;
if (!(in >> c)) { cerr << "missing link cost " << name(x) << "-" << name(y) << "\n"; return 2; }
if (c >= 0) g.cost[x][y] = g.cost[y][x] = c;
}
cout << "routers: " << g.n << ", infinity = " << INF << ", poison reverse = " << (poison ? "on" : "off") << "\nlinks:";
for (int x = 0; x < g.n; x++)
for (int y = x + 1; y < g.n; y++)
if (g.cost[x][y] >= 0) cout << " " << name(x) << "-" << name(y) << "=" << g.cost[x][y];
cout << "\n\n";
initTables(g);
converge(g, "initial convergence");
string cmd;
while (in >> cmd) {
string a, b;
if (cmd == "fail") {
in >> a >> b;
int x = routerIndex(a, g.n), y = routerIndex(b, g.n);
g.cost[x][y] = g.cost[y][x] = -1;
cout << "\n";
converge(g, "link " + a + "-" + b + " fails");
} else if (cmd == "cost") {
int c; in >> a >> b >> c;
int x = routerIndex(a, g.n), y = routerIndex(b, g.n);
g.cost[x][y] = g.cost[y][x] = c;
cout << "\n";
converge(g, "link " + a + "-" + b + " cost becomes " + to_string(c));
} else { cerr << "unknown command: " << cmd << "\n"; return 2; }
}
return 0;
}
When a link breaks, routers can count to infinity
Everything so far was good news: new links, shorter routes. DVR handles good news well and bad news badly. Take three routers in a line, A – B – C, all links cost 1, with the input in chain-three.txt. Everyone knows how to reach C. Now the link between B and C fails.
B loses its direct route to C immediately. But A is still telling B that it can reach C in 2 — and A’s route to C goes through B. B cannot tell that A’s claim depends on B itself, so it believes it: 1 + 2 = 3, via A. Next round A hears B’s 3 and updates to 4. Each router keeps raising its estimate on the strength of the other’s. Here is the real run (03-count-to-infinity.txt); read the A= and B= columns downwards, with the next hop in brackets:
== link B-C fails ==
round 0 | to C: A=2(B) B=1(C)
round 1 | to C: A=2(B) B=3(A)
round 2 | to C: A=4(B) B=3(A)
round 3 | to C: A=4(B) B=5(A)
round 4 | to C: A=6(B) B=5(A)
round 5 | to C: A=6(B) B=7(A)
round 6 | to C: A=8(B) B=7(A)
round 7 | to C: A=8(B) B=9(A)
round 8 | to C: A=10(B) B=9(A)
round 9 | to C: A=10(B) B=11(A)
round 10 | to C: A=12(B) B=11(A)
round 11 | to C: A=12(B) B=13(A)
round 12 | to C: A=14(B) B=13(A)
round 13 | to C: A=14(B) B=15(A)
round 14 | to C: A=INF B=15(A)
round 15 | to C: A=INF B=INF
converged: round 16 changed nothing
rounds that changed something: 15
check vs Floyd-Warshall: match
The estimates climb by 2 every two rounds until they hit 16, the ceiling the simulator (like RIP) calls infinity, and only then do both routers admit that C is unreachable: 15 rounds of wrong routing, during which packets for C bounce between A and B. The ceiling is the only thing that stops it, which is why the maximum has to be small.
The fingerprint of count-to-infinity. Two routers each list the other as the next hop for the same destination, and the distance to it rises round after round. If you ever see a destination whose cost keeps growing while its next hop points back and forth between two neighbours, this is what you are looking at.
The classic fix is poison reverse: a router tells a neighbour “infinity” for any destination it reaches through that neighbour. A reaches C through B, so it tells B that C is unreachable, and B no longer builds a route on A’s stale claim. Same input, --poison flag (04-poison-reverse.txt):
== link B-C fails ==
round 0 | to C: A=2(B) B=1(C)
round 1 | to C: A=2(B) B=INF
round 2 | to C: A=INF B=INF
converged: round 3 changed nothing
rounds that changed something: 2
check vs Floyd-Warshall: match
Two rounds instead of fifteen. The relevant line in the code is if (poison && snapNext[v][y] == x) advertised = INF;.
Poison reverse is not a cure-all. It breaks loops between two routers. RFC 2453 says plainly that it does not prevent loops among three or more routers; those are only resolved when the metric reaches infinity, which is why triggered updates exist (section 3.4.3 and 3.4.4). The runs here only cover the two-router case and a line topology, so they do not demonstrate that limit.
Intermediate: a four-router line that splits in two
A – B – C – D with the middle link failing, so A and B lose D (partition.txt). With poison reverse the news travels in two rounds (05-partition-poison.txt):
== link B-C fails ==
round 0 | to D: A=3(B) B=2(C) C=1(D)
round 1 | to D: A=3(B) B=INF C=1(D)
round 2 | to D: A=INF B=INF C=1(D)
converged: round 3 changed nothing
rounds that changed something: 2
check vs Floyd-Warshall: match
Without it, A and B count up again. The last rounds of that run, from 06-partition-plain.txt, show the same 15-round pattern with A and B pointing at each other:
round 12 | to D: A=15(B) B=14(A) C=1(D)
round 13 | to D: A=15(B) B=INF C=1(D)
round 14 | to D: A=INF B=INF C=1(D)
round 15 | to D: A=INF B=INF C=1(D)
converged: round 16 changed nothing
rounds that changed something: 15
check vs Floyd-Warshall: match
The pattern is always the same. Whichever router is cut off from a destination first keeps getting “good” news from a neighbour whose route runs through it.
The two earlier versions of this program were wrong in ways you can run
This post replaces two earlier posts on this site with the same title. The comparison is worth keeping, because the bugs are instructive. Both programs are preserved in the repository under legacy/; nothing was rewritten to make them look better or worse.
The 2015 program (the one that used to live at this URL) was written for a 1990s compiler: iostream.h, conio.h and void main. A modern compiler stops at the first line (09-legacy-2015-compile-error.txt):
legacy/old_dvr_2015_turbocpp.cpp:1:9: fatal error: iostream.h: No such file or directory
1 | #include<iostream.h>
| ^~~~~~~~~~~~
compilation terminated.
The 2025 program compiles and finds correct distances, but its Via column is wrong. The post printed “B→D, 5, via C” in its sample output. Running the program on the same four-node network prints a dash for every destination, meaning “direct link”, even for destinations B has no link to (10-legacy-four-node-via-column.txt). The sample output on the old page did not match what the code prints.
B Routing Table
Node Dist Via
A 1 -
B 0 -
C 2 -
D 5 -
On a five-router chain the problem is easier to see. Router A has no link to C, D or E, yet the old program claims it reaches all of them directly (08-legacy-wrong-next-hop.txt). The new simulator gives the right answer for the same network, with B as A’s next hop for everything (07-chain-five-dvr.txt):
A Routing Table
Node Dist Via
A 0 -
B 1 -
C 2 -
D 3 -
E 4 -
A Routing Table
Dest Dist Next hop
A 0 -
B 1 B
C 2 B
D 3 B
E 4 B
From reading the code, the cause is that after the first sweep the program copies its best distances back into the matrix it treats as “direct links”, and every later sweep resets the next-hop entry to the router itself. After the first sweep it can no longer tell a real link from a route it learned. The new simulator keeps the link costs and the learned distances apart.
Preserved: the original 2015 program and how it worked
Kept for reference exactly as it was published (it does not compile with a current compiler). File: legacy/old_dvr_2015_turbocpp.cpp.
#include<iostream.h>
#include<conio.h>
void main()
{
int graph[50][50];
int i,j,k,t;
int nn;
cout<<"\n Enter Number of Nodes:";
cin>>nn;
/* Initialize graph*/
for (i=0;i<nn;i++)
{
for(j=0;j<nn;j++)
{
graph[i][j]=-1;
}
}
/* Vertex names */
char ch[7]={'A','B','C','D','E','F','G'};
/* Get input */
for (i=0;i<nn;i++)
{
for(j=0;j<nn;j++)
{
if(i==j)
{
graph[i][j]=0;
}
if(graph[i][j]==-1)
{
cout<<"\n Enter Distance between "<<ch[i]<<" - "<<ch[j]<<" : ";
cin>>t;
graph[i][j]=graph[j][i]=t;
}
}
}
/* Initializing via */
int via[50][50];
for (i=0;i<nn;i++)
{
for(j=0;j<nn;j++)
{
via[i][j]=-1;
}
}
cout<<"\n After Initialization";
/* Display table initialization */
for (i=0;i<nn;i++)
{
cout<<"\n"<<ch[i]<<" Table";
cout<<"\nNode\tDist\tVia";
for(j=0;j<nn;j++)
{
cout<<"\n"<<ch[j]<<"\t"<<graph[i][j]<<"\t"<<via[i][j];
}
}
//sharing table
int sh[50][50][50];
for(i=0;i<nn;i++)
{
for(j=0;j<nn;j++)
{
for (k=0;k<nn;k++)
{
/* Check if edge is present or not*/
if((graph[i][j]>-1)&&(graph[j][k]>-1))
{
sh[i][j][k]=graph[j][k]+graph[i][j];
}
else
{
sh[i][j][k]=-1;
}
}
}
}
/*displaying shared table */
for(i=0;i<nn;i++)
{
cout<<"\n\n For "<<ch[i];
for (j=0;j<nn;j++)
{
cout<<"\n From "<<ch[j];
for(k=0;k<nn;k++)
{
cout<<"\n "<<ch[k]<<" "<<sh[i][j][k];
}
}
}
/* Updating */
int final[50][50];
for(i=0;i<nn;i++)
{
for(j=0;j<nn;j++)
{
/* Copy initial value from input graph*/
final[i][j]=graph[i][j];
via[i][j]=i;
/*Update them*/
/* Check condition a - b - c */
for(k=0;k<nn;k++)
{
if((final[i][j]>sh[i][k][j]) || (final[i][j] == -1))
{
if(sh[i][k][j]>-1)
{
final[i][j]=sh[i][k][j];
via[i][j]=k;
}
}
}
/* After considering three vertex if final not found
consider 4th
a- b- c- d
*/
if(final[i][j]==-1)
{
for(k=0;k<nn;k++)
{
if((final[i][k]!=-1)&&(final[k][j]!=-1))
{
if((final[i][j]==-1) || ((final[i][j]!=-1) &&(final[i][j]>final[i][k]+final[k][j])))
{
if(final[i][k]+final[k][j]>-1)
{
final[i][j]=final[i][k]+final[k][j];
via[i][j]=k;
}
}
}
}
}
}
}
cout<<"\n After Update :";
/* Display table Updation */
for (i=0;i<nn;i++)
{
cout<<"\n"<<ch[i]<<" Table";
cout<<"\nNode\tDist\tVia";
for(j=0;j<nn;j++)
{
cout<<"\n"<<ch[j]<<"\t"<<final[i][j]<<"\t";
if(i==via[i][j])
cout<<"-";
else
cout<<ch[via[i][j]];
}
}
getch();
}
/* OUTPUT
Enter Number of Nodes:5
Enter Distance between A - B : 5
Enter Distance between A - C : 2
Enter Distance between A - D : 3
Enter Distance between A - E : -1
Enter Distance between B - C : 4
Enter Distance between B - D : -1
Enter Distance between B - E : 3
Enter Distance between C - D : -1
Enter Distance between C - E : 4
Enter Distance between D - B : -1
Enter Distance between D - C : -1
Enter Distance between D - E : -1
Enter Distance between E - A : -1
Enter Distance between E - D : -1
After Initialization
A Table
Node Dist Via
A 0 -1
B 5 -1
C 2 -1
D 3 -1
E -1 -1
B Table
Node Dist Via
A 5 -1
B 0 -1
C 4 -1
D -1 -1
E 3 -1
C Table
Node Dist Via
A 2 -1
B 4 -1
C 0 -1
D -1 -1
E 4 -1
D Table
Node Dist Via
A 3 -1
B -1 -1
C -1 -1
D 0 -1
E -1 -1
E Table
Node Dist Via
A -1 -1
B 3 -1
C 4 -1
D -1 -1
E 0 -1
For A
From A
A 0
B 5
C 2
D 3
E -1
From B
A 10
B 5
C 9
D -1
E 8
From C
A 4
B 6
C 2
D -1
E 6
From D
A 6
B -1
C -1
D 3
E -1
From E
A -1
B -1
C -1
D -1
E -1
For B
From A
A 5
B 10
C 7
D 8
E -1
From B
A 5
B 0
C 4
D -1
E 3
From C
A 6
B 8
C 4
D -1
E 8
From D
A -1
B -1
C -1
D -1
E -1
From E
A -1
B 6
C 7
D -1
E 3
For C
From A
A 2
B 7
C 4
D 5
E -1
From B
A 9
B 4
C 8
D -1
E 7
From C
A 2
B 4
C 0
D -1
E 4
From D
A -1
B -1
C -1
D -1
E -1
From E
A -1
B 7
C 8
D -1
E 4
For D
From A
A 3
B 8
C 5
D 6
E -1
From B
A -1
B -1
C -1
D -1
E -1
From C
A -1
B -1
C -1
D -1
E -1
From D
A 3
B -1
C -1
D 0
E -1
From E
A -1
B -1
C -1
D -1
E -1
For E
From A
A -1
B -1
C -1
D -1
E -1
From B
A 8
B 3
C 7
D -1
E 6
From C
A 6
B 8
C 4
D -1
E 8
From D
A -1
B -1
C -1
D -1
E -1
From E
A -1
B 3
C 4
D -1
E 0
After Update :
A Table
Node Dist Via
A 0 -
B 5 -
C 2 -
D 3 -
E 6 C
B Table
Node Dist Via
A 5 -
B 0 -
C 4 -
D 8 A
E 3 -
C Table
Node Dist Via
A 2 -
B 4 -
C 0 -
D 5 A
E 4 -
D Table
Node Dist Via
A 3 -
B 8 A
C 5 A
D 0 -
E 9 A
E Table
Node Dist Via
A 6 C
B 3 -
C 4 -
D 9 A
E 0 -
*/
The 2015 explanation went in five steps: (1) a 50×50 graph array initialised to -1 with zeros on the diagonal; (2) the user typing each pairwise distance; (3) a via table initialised to -1 holding next hops; (4) a 3-D array sh[i][j][k] holding what node i would learn from neighbour j about destination k, computed as graph[i][j] + graph[j][k] when both links exist; (5) updating the final table by taking the minimum over those shared values, and adding a fourth-node pass when no route had been found. Its sample run used the five-router network above and showed A reaching E in 6 via C, which the new simulator reproduces in 02-five-node-trace.txt.
Preserved: the 2025 program
The 2025 version of this post used a flat-array version without the 3-D array. Distances are correct; the Via column is not, as shown above. File: legacy/old_dvr_global_matrix.cpp.
#include <iostream>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max(); // Represents no known path
int main()
{
int nodeCount;
cout << "\n Enter Number of Nodes: ";
cin >> nodeCount;
// directDist[src][dst] = direct link cost between src and dst (INF if no direct link)
int directDist[50][50];
for (int src = 0; src < nodeCount; src++)
{
for (int dst = 0; dst < nodeCount; dst++)
{
directDist[src][dst] = (src == dst) ? 0 : INF;
}
}
// Assign node labels A, B, C, D, ...
char nodeName[50];
for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
{
nodeName[nodeIndex] = 'A' + nodeIndex;
}
// Read direct link distances between each pair of nodes
for (int src = 0; src < nodeCount; src++)
{
for (int dst = src + 1; dst < nodeCount; dst++)
{
int linkCost;
cout << "\n Enter Distance between "
<< nodeName[src] << " - " << nodeName[dst]
<< " (use -1 for no connection): ";
cin >> linkCost;
if (linkCost != -1)
{
directDist[src][dst] = linkCost;
directDist[dst][src] = linkCost; // Assume symmetric (undirected) links
}
}
}
// viaNode[src][dst] = intermediate node used on the current best path from src to dst
int viaNode[50][50];
for (int src = 0; src < nodeCount; src++)
for (int dst = 0; dst < nodeCount; dst++)
viaNode[src][dst] = -1;
// bestDist[src][dst] = best known shortest distance from src to dst
int bestDist[50][50];
// --- Iterative Distance Vector update loop ---
bool updated;
do
{
updated = false;
for (int src = 0; src < nodeCount; src++)
{
for (int dst = 0; dst < nodeCount; dst++)
{
bestDist[src][dst] = directDist[src][dst];
viaNode[src][dst] = src; // Default: reach dst directly from src
// Try routing through each intermediate node k
for (int via = 0; via < nodeCount; via++)
{
if (directDist[src][via] != INF && directDist[via][dst] != INF)
{
int candidateDist = directDist[src][via] + directDist[via][dst];
if (candidateDist < bestDist[src][dst])
{
bestDist[src][dst] = candidateDist;
viaNode[src][dst] = via;
updated = true;
}
}
}
}
}
// Propagate the improved distances back into directDist for the next iteration
for (int src = 0; src < nodeCount; src++)
for (int dst = 0; dst < nodeCount; dst++)
directDist[src][dst] = bestDist[src][dst];
} while (updated); // Repeat until no further improvements (convergence)
// --- Print final routing tables ---
cout << "\n After Convergence:";
for (int src = 0; src < nodeCount; src++)
{
cout << "\n\n" << nodeName[src] << " Routing Table";
cout << "\n Node\tDist\tVia";
for (int dst = 0; dst < nodeCount; dst++)
{
cout << "\n" << nodeName[dst] << "\t";
if (bestDist[src][dst] == INF)
cout << "INF";
else
cout << bestDist[src][dst];
cout << "\t";
if (src == viaNode[src][dst])
cout << "-"; // Direct connection, no intermediate hop
else
cout << nodeName[viaNode[src][dst]];
}
}
cout << "\n";
return 0;
}
Should you build routing this way?
For learning, yes; for a real network, almost never. Distance vector routing is the right first algorithm to understand because each router needs only its neighbours, and the code is short. But RIP, its best-known descendant, tops out at 15 hops and converges slowly, and the count-to-infinity problem is why. Larger networks use link-state protocols such as OSPF, where every router floods its links and runs Dijkstra on the full map (RFC 2328), and between organisations the internet uses BGP, a path-vector protocol that carries the whole path with each route so that loops are visible (RFC 4271). This simulator is a teaching tool: it is synchronous, has no timers, no triggered updates and no packet forwarding.
Exam and interview notes
Why is it called “distance vector”? Each router advertises a vector of (destination, distance) pairs to its neighbours.
What does a router need to know? Only the costs of its own links and the vectors its neighbours send. It never learns the full topology.
How many rounds to converge? In a static network, as many as the longest best path has links, minus one (as shown above: three rounds for a four-link chain). This counts synchronous rounds; real networks depend on update timers.
What is count-to-infinity and how do you limit it? Routers raise each other’s estimates after a failure. Limit it with a small maximum metric (16 in RIP), split horizon with poison reverse, and triggered updates.
Distance vector versus link state? Distance vector shares its own table with neighbours only; link state floods link information to every router, which then computes shortest paths itself.
https://en.wikipedia.org/wiki/Distance-vector_routing_protocol
Ur code gives partially wrong answer for example in this link.
The code is only running for one time i.e., at t=1 it stops