Distance Vector Algorithm

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

#include <stdio.

h>

#include <limits.h>

#define MAX_NODES 10

// Function to find the minimum of two numbers

int min(int a, int b) {

return (a < b) ? a : b;

// Function to perform distance vector routing

void distanceVectorRouting(int graph[MAX_NODES][MAX_NODES], int nodes) {

int distance[MAX_NODES][MAX_NODES];

// Initializing distance matrix

for (int i = 0; i < nodes; i++) {

for (int j = 0; j < nodes; j++) {

distance[i][j] = graph[i][j];

// Output the original distance matrix

printf("Original distance matrix:\n");

for (int i = 0; i < nodes; i++) {

for (int j = 0; j < nodes; j++) {

printf("%d\t", graph[i][j]);

printf("\n");

// Updating distance matrix using distance vector routing algorithm


for (int k = 0; k < nodes; k++) {

for (int i = 0; i < nodes; i++) {

for (int j = 0; j < nodes; j++) {

if (distance[i][k] != INT_MAX && distance[k][j] != INT_MAX) {

distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]);

// Output the shortest distance matrix

printf("\nShortest distance matrix:\n");

for (int i = 0; i < nodes; i++) {

for (int j = 0; j < nodes; j++) {

printf("%d\t", distance[i][j]);

printf("\n");

// Input two nodes to find the shortest path and distance

int source, destination;

printf("\nEnter source node: ");

scanf("%d", &source);

printf("Enter destination node: ");

scanf("%d", &destination);

// Output the shortest path and distance

printf("Shortest distance from node %d to node %d: %d\n", source, destination, distance[source]
[destination]);

int main() {
int nodes;

// Input the number of nodes

printf("Enter the number of nodes: ");

scanf("%d", &nodes);

int graph[MAX_NODES][MAX_NODES];

// Input distances between nodes

printf("Enter the distance matrix (use 'INT_MAX' for infinity):\n");

for (int i = 0; i < nodes; i++) {

for (int j = 0; j < nodes; j++) {

scanf("%d", &graph[i][j]);

// Perform distance vector routing and find shortest path and distance

distanceVectorRouting(graph, nodes);

return 0;

You might also like