0% found this document useful (0 votes)
14 views3 pages

CN 9 Ex

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

CN 9 Ex

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Import java.util.

Scanner;
Public class DistanceVectorRouting {
Private static final int INF = 999; // Infinity, used for unreachable nodes
Private int numNodes;
Private int[][] distanceMatrix;
Private int[][] routingTable;
// Constructor to initialize the network
Public DistanceVectorRouting(int numNodes) {
This.numNodes = numNodes;
This.distanceMatrix = new int[numNodes][numNodes];
This.routingTable = new int[numNodes][numNodes];
}
// Function to initialize the distance matrix and routing table
Public void initialize(Scanner sc) {
System.out.println(“Enter the distance matrix (Enter 999 for no direct
connection):”);
For (int I = 0; I < numNodes; i++) {
For (int j = 0; j < numNodes; j++) {
distanceMatrix[i][j] = sc.nextInt();
// Initialize routing table to distance matrix values
routingTable[i][j] = distanceMatrix[i][j];
}
}
}
// Function to perform the distance vector algorithm
Public void distanceVectorAlgorithm() {
For (int k = 0; k < numNodes; k++) { // Repeat for convergence
For (int I = 0; I < numNodes; i++) {
For (int j = 0; j < numNodes; j++) {
// Update routing table if a shorter path is found through node k
If (routingTable[i][j] > routingTable[i][k] + routingTable[k][j]) {
routingTable[i][j] = routingTable[i][k] + routingTable[k][j];
}
}
}
}
}
// Function to display the routing tables
Public void displayRoutingTables() {
For (int I = 0; I < numNodes; i++) {
System.out.println(“\nRouting table for Node “ + (I + 1) + “:”);
For (int j = 0; j < numNodes; j++) {
If (routingTable[i][j] == INF) {
System.out.print(“INF\t”);
} else {
System.out.print(routingTable[i][j] + “\t”);
}
}
System.out.println();
}
}
Public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input number of nodes
System.out.print(“Enter the number of nodes: “);
Int numNodes = sc.nextInt();
DistanceVectorRouting dvr = new DistanceVectorRouting(numNodes);
Dvr.initialize(sc); // Initialize the network
Dvr.distanceVectorAlgorithm(); // Perform the Distance Vector algorithm
Dvr.displayRoutingTables(); // Display the updated routing tables
Sc.close();
}
}

You might also like