0% found this document useful (0 votes)
23 views34 pages

WMC Lab

The document outlines four experiments related to sensor networks and routing protocols, including the creation of sensor nodes, implementation of shortest path algorithms, and distance vector and link state routing protocols. Each experiment includes a specific aim, theoretical background, code implementation, and learning outcomes. Key concepts such as Dijkstra's algorithm, Bellman-Ford algorithm, and the mechanics of distance vector and link state routing are discussed.

Uploaded by

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

WMC Lab

The document outlines four experiments related to sensor networks and routing protocols, including the creation of sensor nodes, implementation of shortest path algorithms, and distance vector and link state routing protocols. Each experiment includes a specific aim, theoretical background, code implementation, and learning outcomes. Key concepts such as Dijkstra's algorithm, Bellman-Ford algorithm, and the mechanics of distance vector and link state routing are discussed.

Uploaded by

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

Experiment 1

AIM :
WAP to create sensor nodes and establish communication between them.

THEORY :
A sensor network is a group of specialized devices (nodes) that detect environmental
conditions like temperature, humidity, pressure, etc., and share this data with other
nodes or a central hub. As sensor nodes may be randomly deployed in interest, they
must be aware of their locations to provide meaningful data to the users.
Components of WSN:
1. Sensors: Sensors in WSN are used to capture the environmental variables and
which are used for data acquisition. Sensor signals are converted into electrical
signals.
2. Radio Nodes: It is used to receive the data produced by the Sensors and sends
it to the WLAN access point. It consists of a microcontroller, transceiver,
external memory, and power source.
3. WLAN Access Point: It receives the data which is sent by the Radio nodes
wirelessly, generally through the internet.
4. Evaluation Software: The data received by the WLAN Access Point is processed
by a software called Evaluation Software for presenting the report to the users
for further processing of the data, which can be used for processing, analysis,
storage, and mining of the data.

CODE :
#include <bits/stdc++.h>

using namespace std;

bool check(vector<vector<int>> &v, int n)

int a = 1;

for (int i = 0; i < n; i++)

for (int j = i; j < n; j++)


{

if (a & v[i][j] == 0)

return false;

return true;

int main()

int sensor_count;

cout << "Enter the number of sensor nodes : ";

cin >> sensor_count;

vector<vector<int>> v(sensor_count, vector<int>(sensor_count));

cout << "Enter the graph in adjacency matrix format to create connections : \n";

for (int i = 0; i < sensor_count; i++)

for (int j = 0; j < sensor_count; j++)

cin >> v[i][j];

cout << "Is graph all nodes connected to each other : ";

if (check(v, sensor_count))

cout

<< "YES"

<< endl;

else

cout << "NO" << endl;

OUTPUT :
LEARNING OUTCOME :
• Wireless sensor networks are self-configured and infrastructure less/ad-hoc
networks.
• There is no central node. Each node must perform all the tasks such as sending,
receiving, and analyzing data.
• We learned how sensor nodes are connected in a network and how they
communicate with each other.
Experiment 2
AIM :
WAP to implement shortest path algorithm in a sensor network.

THEORY :
Some algorithm can be used here As Dijkstra’s algorithm and Bellman ford algorithm .
Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a
graph, which may represent, for example, road networks. It was conceived by
computer scientist Edsger W. Dijkstra in 1956 and published three years later.
The algorithm exists in many variants. Dijkstra's original algorithm found the shortest
path between two given nodes, but a more common variant fixes a single node as the
"source" node and finds the shortest paths from the source to all other nodes in the
graph, producing a shortest-path tree.
Dijkstra’s algorithm is the iterative algorithmic process to provide us with the shortest
path from one specific starting node to all other nodes of a graph. It is different from
the minimum spanning tree as the shortest distance among two vertices might not
involve all the graph's vertices.
It is important to note that Dijkstra’s algorithm is only applicable when all weights are
positive because, during the execution, the weights of the edges are added to find
the shortest path.
Bellman-Ford algorithm finds the minimum distance from the source vertex to any
other vertex. The main difference between this algorithm with Dijkstra’s algorithm is
in Dijkstra’s algorithm, we cannot handle the negative weight, but here we can handle
it easily.

CODE :
#include <bits/stdc++.h>

using namespace std;

int NO_PARENT = -1;

const int maxDistance = INT32_MAX;

void showThePath(int currentVertex, vector<int> parents)


{

if (currentVertex == NO_PARENT)

return;

showThePath(parents[currentVertex], parents);

cout << currentVertex << " ";

void printSolution(int startVertex, vector<int> distances, vector<int> parents)

int nVertices = distances.size();

cout << "Vertex\t\tDist.\tPath";

for (int vertexIndex = 0; vertexIndex < nVertices; vertexIndex++)

if (vertexIndex != startVertex)

cout << "\n";

cout << vertexIndex << " \t\t";

cout << distances[vertexIndex] << "\t";

showThePath(vertexIndex, parents);

pair<vector<int>, vector<int>> findShortestPath(vector<vector<int>> &adjMatrix, int startNode)

int numNodes = adjMatrix.size();

vector<int> minDistances(numNodes, maxDistance);

vector<int> parentNode(numNodes, startNode);

vector<bool> visited(numNodes, false);

minDistances[startNode] = 0;

parentNode[startNode] = NO_PARENT;
for (int step = 0; step < numNodes - 1; step++)

int currentMin = maxDistance, currentNode = -1;

for (int i = 0; i < numNodes; i++)

if (!visited[i] && minDistances[i] < currentMin)

currentNode = i;

currentMin = minDistances[i];

visited[currentNode] = true;

for (int j = 0; j < numNodes; j++)

if ((adjMatrix[currentNode][j] > 0) && (adjMatrix[currentNode][j] != maxDistance) &&


minDistances[currentNode] + adjMatrix[currentNode][j] < minDistances[j])

minDistances[j] = minDistances[currentNode] + adjMatrix[currentNode][j];

parentNode[j] = currentNode;

return {parentNode, minDistances};

// Driver Code

int main()

vector<vector<int>> adjacencyMatrix =

{{2, 14, 8, 0, 0, 4, 0, 8, 0},

{3, 0, 8, 0, 0, 0, 0, 11, 0},

{0, 6, 0, 7, 5, 4, 0, 0, 2},

{0, 0, 7, 0, 9, 54, 20, 0, 0},


{0, 0, 9, 9, 0, 10, 0, 0, 0},

{0, 0, 4, 0, 8, 2, 20, 0, 12},

{0, 0, 0, 24, 0, 2, 0, 1, 2},

{8, 11, 0, 0, 0, 0, 1, 0, 5},

{0, 0, 2, 8, 90, 10, 26, 7, 0}};

int src;

cout << "Enter source node : ";

cin >> src;

pair<vector<int>, vector<int>> shortest_paths = findShortestPath(adjacencyMatrix, src);

printSolution(src, shortest_paths.second, shortest_paths.first);

return 0;

OUTPUT :

LEARNING OUTCOME :
• Graphs are used to model connections between objects, people, or entities.
They have two main elements: nodes and edges. Nodes represent objects and
edges represent the connections between these objects.
• Dijkstra's Algorithm finds the shortest path between a given node (which is
called the "source node") and all other nodes in a graph.
• This algorithm uses the weights of the edges to find the path that minimizes
the total distance (weight) between the source node and all other nodes.
Experiment 3
AIM :
WAP to implement Distance Vector Routing Protocol

THEORY :
In distance-vector routing (DVR), each router is required to inform the topology
changes to its neighbouring routers periodically. Historically it is known as the old
ARPNET routing algorithm or Bellman-Ford algorithm.
How the DVR Protocol Works: In DVR, each router maintains a routing table. It
contains only one entry for each router. It includes two parts − a preferred outgoing
line to use for that destination and an estimate of time (delay). Tables are updated by
exchanging the information with the neighbour’s nodes.
Each router knows the delay in reaching its neighbours (Ex − sending echo requests).
Routers periodically exchange routing tables with each of their neighbours. It
compares the delay in its local table with the delay in the neighbour’s table and the
cost of reaching that neighbour. If the path via the neighbour has a lower cost, then
the router updates its local table to forward packets to the neighbour .

CODE :
#include <bits/stdc++.h>

using namespace std;

void printGraphOfAdjacencyMatrix(vector<vector<int>> &graph)

int n = graph.size();

cout << " ";

for (int i = 0; i < n; i++)

printf("%3c", ('A' + i));

cout << "\n";

for (int i = 0; i < n; i++)

{
cout << (char)('A' + i);

for (int j = 0; j < n; j++)

if (graph[i][j] == INT_MAX)

printf("%3d", -1);

else

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

cout << "\n";

cout << "\n\n";

void solve(vector<vector<int>> &ans, vector<int> neighbores[])

int n = ans.size();

cout << "After 1st iteration : \n\n";

printGraphOfAdjacencyMatrix(ans);

for (int k = 0; k < n - 2; k++)

vector<vector<int>> prev = ans;

for (int start_node = 0; start_node < n; start_node++)

for (int j = 0; j < n; j++)

ans[start_node][j] = prev[start_node][j];

for (int t = 0; t < neighbores[start_node].size(); t++)

int y = neighbores[start_node][t];

int val;

if (prev[start_node][y] == INT_MAX || prev[y][j] == INT_MAX)

val = INT_MAX;

else
val = prev[start_node][y] + prev[y][j];

ans[start_node][j] = min(ans[start_node][j], val);

string number_prefix = "rd";

if (k + 2 > 3)

number_prefix = "th";

cout << "After " << k + 2 << number_prefix << " iteration : \n\n";

printGraphOfAdjacencyMatrix(ans);

int main()

int inf = INT_MAX;

cout << "\n----> Distance Vector Routing Algorithm\n\n";

vector<vector<int>> graph_step = {{0, inf, inf, 1}, {1, 1, 1, 7}, {inf, 7, inf, 6}, {12, 8, inf, 8}};

int sz = graph_step.size();

vector<int> neighbors[sz];

for (int i = 0; i < sz; i++)

for (int j = 0; j < sz; j++)

if (graph_step[i][j] != INT_MAX)

neighbors[i].push_back(j);

}
solve(graph_step, neighbors);

return 0;

OUTPUT :

LEARNING OUTCOME :
1) DVR protocol uses Bellman ford algorithm to find the shortest path to the
destination node.
2) In the distance vector routing protocol, only distance vector information is
exchanged and next-hop values are not exchanged.
3) The process of updating the routing table keeps on repeating periodically to
update the shortest path in case the link goes down or there is a topology
change.
4) Distance vector routing faces an account-to-infinity prob.
Experiment 4
AIM :
WAP to implement Link State Routing Protocol

THEORY :
Link state routing is a technique in which each router shares the knowledge of its
neighbourhood with every other router on the internetwork.
The three keys to understanding the Link State Routing algorithm:
1. Knowledge about the neighbourhood: Instead of sending its routing table, a
router sends the information about its neighbourhood only. A router
broadcasts its identities and cost of the directly attached links to other routers.
2. Flooding: Each router sends the information to every other router on the
internetwork except its neighbours. This process is known as Flooding. Every
router that receives the packet sends copies to all its neighbours. Finally, each
and every router receives a copy of the same information.
3. Information sharing: A router sends the information to every other router only
when the change occurs in the information.

CODE :
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>

using namespace std;


vector<char> ch = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'};
int column_size = 10;
int inf = INT32_MAX;

void printSPT(vector<int> &dist, vector<int> &parent)


{
int V = dist.size();
cout << "Path calculated =" << endl;
for (int i = 0; i < V; i++)
{
vector<int> path;
for (int u = i; u != -1; u = parent[u])
path.push_back(u);
reverse(path.begin(), path.end());
cout <<ch[i] << ": ";
for (int p = 0; p < path.size() - 1; p++)
cout << ch[path[p]] << "->";
cout << ch[path[path.size() - 1]] << "\n";
}
}
pair<vector<int>, vector<int>> dijkstra_path_search(vector<vector<int>> &graph, int src)
{
int V = graph.size();
vector<int> dist(V, inf);
vector<int> parent(V, src);
vector<bool> flag(V, false);

dist[src] = 0;
parent[src] = -1;
for (int c = 0; c < V - 1; c++)
{
int minVal = inf, minIndex;
for (int i = 0; i < V; i++)
{
if (flag[i] == false and dist[i] < minVal)
{

minIndex = i;
minVal = dist[i];
}
}
int u = minIndex;
flag[u] = true;
for (int v = 0; v < V; v++)
{
if (!flag[v] and graph[u][v] != inf and dist[u] + graph[u][v] < dist[v])
{
dist[v] = dist[u] + graph[u][v];
parent[v] = u;
}
}
}
cout << "\nSPT for router " << ch[src] << ":\n";
printSPT(dist, parent);
return {parent, dist};
}

bool isInfiniteEdge(int check)


{
// Input graph condition to be direct unreachable
if (check < 0)
return true;
else
return false;
}
vector<vector<int>> graphInput()
{
int V;
cout << "\nEnter number of nodes in the routing : ";
cin >> V;
vector<vector<int>> graph(V, vector<int>(V, -1));

for (int i = 0; i < V; i++)


{
cout << "Enter space separated edge distance from node = " << i << " (Less than 0 if nodes are not connected ):\n";
for (int j = 0; j < V; j++)
{
cin >> graph[i][j];
if (isInfiniteEdge(graph[i][j]))
graph[i][j] = inf;
}
}
return graph;
}

void buildRoutingTable(vector<int> &parent, vector<int> &dist,


int src)
{

int nodes_1 = dist.size();


cout << "\nRouting table for "
<< ch[src] << ":\n";
cout << setw(column_size) << "To" << setw(column_size) << "Dist" << setw(column_size) << "Via" << endl;
for (int i = 0; i < nodes_1; i++)
{
int memo = i;
for (int u = i; parent[u] != -1; u = parent[u])
memo = u;
cout << setw(column_size) << ch[i] << setw(column_size) << dist[i];
if (memo == i)
cout << setw(column_size) << "-" << endl;
else
cout << setw(column_size) << ch[memo] << endl;
}
}
int main()
{
vector<vector<int>> graph_step = graphInput();
int V = graph_step.size();
for (int source_node = 0; source_node < V; source_node++)
{
auto p = dijkstra_path_search(graph_step, source_node);
vector<int> parent = p.first;
vector<int> dist = p.second;
buildRoutingTable(parent, dist, source_node);
}

return 0;
}
OUTPUT :
LEARNING OUTCOME :
• The Link State Routing protocol uses Dijkstra’s Algorithm to find the shortest
path from source to destination.
• The link state routing algorithm exchanges information only when there is a
change in the connection.
• It requires large memory as it maintains a routing database.
• It requires the computation of the shortest path, which is an overhead for the
CPU.
The information of each router needs to be transmitted all over the network.
Experiment 5
AIM :
WAP to implement AODV Routing Protocol

THEORY :
An Ad Hoc On-Demand Distance Vector (AODV) is a routing protocol designed for
wireless and mobile ad hoc networks. This protocol establishes routes to destinations
on demand and supports both unicast and multicast routing. The AODV protocol was
jointly developed by the Nokia Research Centre, the University of California, Santa
Barbara, and the University of Cincinnati in 1991.
The AODV protocol builds routes between nodes only if they are requested by source
nodes. AODV is therefore considered an on-demand algorithm and does not create
any extra traffic for communication along links. The routes are maintained as long as
the sources require them. They also form trees to connect multicast group members.
AODV makes use of sequence numbers to ensure route freshness. They are self-
starting and loop-free, besides scaling to numerous mobile nodes.
The advantage of source routing is: intermediate nodes do not need to maintain up-
to-date routing information to route the packets they forward.

CODE :
#include <bits/stdc++.h>

using namespace std;

const int maxDistance = INT_MAX;

int NO_PARENT = -1;

void showThePath(int currentVertex, vector<int> parents)

if (currentVertex == NO_PARENT)

return;

showThePath(parents[currentVertex], parents);
cout << currentVertex << " ";

void printSolution(int source_vertex, vector<int> distances, vector<int> parents, int destination)

int total_vertices = distances.size();

cout << "Vertex\t\tDist.\tPath";

cout << "\n";

cout << destination << " \t\t";

cout << distances[destination] << "\t";

showThePath(destination, parents);

pair<vector<int>, vector<int>> findShortestPath(vector<vector<int>> &adjMatrix, int startNode)

int numNodes = adjMatrix.size();

vector<int> minDistances(numNodes, maxDistance);

vector<int> parentNode(numNodes, startNode);

vector<bool> visited(numNodes, false);

minDistances[startNode] = 0;

parentNode[startNode] = NO_PARENT;

for (int step = 0; step < numNodes - 1; step++)

int currentMin = maxDistance, currentNode = -1;

for (int i = 0; i < numNodes; i++)

if (!visited[i] && minDistances[i] < currentMin)

currentNode = i;

currentMin = minDistances[i];

}
}

visited[currentNode] = true;

for (int j = 0; j < numNodes; j++)

if ((adjMatrix[currentNode][j] > 0) && (adjMatrix[currentNode][j] != maxDistance) &&


minDistances[currentNode] + adjMatrix[currentNode][j] < minDistances[j])

minDistances[j] = minDistances[currentNode] + adjMatrix[currentNode][j];

parentNode[j] = currentNode;

return {parentNode, minDistances};

// Driver Code

int main()

vector<vector<int>> adjacencyMatrix =

{{2, 14, 8, 0, 0, 4, 0, 8, 0},

{3, 0, 8, 0, 0, 0, 0, 11, 0},

{0, 6, 0, 7, 5, 4, 0, 0, 2},

{0, 0, 7, 0, 9, 54, 20, 0, 0},

{0, 0, 90, 29, 0, 10, 0, 0, 0},

{0, 0, 4, 0, 8, 2, 20, 0, 12},

{0, 0, 0, 24, 0, 2, 0, 1, 2},

{8, 11, 0, 0, 0, 0, 1, 0, 5},

{0, 0, 2, 8, 90, 10, 26, 7, 0}};

int src, ed;

cout << "Enter the source and destination node = ";

cin >> src >> ed;

cout << "RREQ multicast messages sent : " << endl;


cout << "RREP containing the full route path :" << endl;

pair<vector<int>, vector<int>> shortest_paths = findShortestPath(adjacencyMatrix, src);

printSolution(src, shortest_paths.second, shortest_paths.first, ed);

return 0;

OUTPUT :

LEARNING OUTCOME :
• In AODV, nodes discover routes in request-response cycles.
• A node requests a route to a destination by broadcasting an RREQ message to
all its neighbours.
• When a node receives an RREQ message but does not have a route to the
requested destination, it in turn broadcasts the RREQ message.
• Also, it remembers a reverse-route to the requesting node which can be used
to forward subsequent responses to this RREQ.
• This process repeats until the RREQ reaches a node that has a valid route to the
destination

Experiment 6
AIM :
WAP to implement DSDV Routing Protocol.

THEORY :
The full form of DSDV is: Destination Sequenced Distance Vector Routing Destination
Sequenced Distance Vector (DSDV) is a hop-by-hop vector routing protocol requiring
each node to periodically broadcast routing updates. This is a table-driven algorithm
based on modifications made to the Bellman-Ford routing mechanism. Each node in
the network maintains a routing table that has entries for each of the destinations in
the network and the number of hops required to reach each of them. Each entry has
a sequence number associated with it that helps in identifying stale entries.
This mechanism allows the protocol to avoid the formation of routing loops. Each
node periodically sends updates tagged throughout the network with a
monotonically increasing even sequence number to advertise its location. New route
broadcasts contain the address of the destination, the number of hops to reach the
destination, and the sequence number of the information received regarding the
destination, as well as a new sequence number unique to the broadcast. The route
labelled with the most recent sequence number is always used. When the neighbours
of the transmitting node receive this update, they recognize that they are one hop
away from the source node and include this information in their distance vectors.

CODE :
#include <bits/stdc++.h>

using namespace std;

void BellmanFord(int graph[][3], int V, int E, int src)

int dis[V];

for (int i = 0; i < V; i++)

dis[i] = INT_MAX;

dis[src] = 0;

for (int i = 0; i < V - 1; i++)

for (int j = 0; j < E; j++)

if (dis[graph[j][0]] != INT_MAX && dis[graph[j][0]] + graph[j][2] < dis[graph[j][1]])

dis[graph[j][1]] = dis[graph[j][0]] + graph[j][2];

for (int i = 0; i < E; i++)


{

int x = graph[i][0];

int y = graph[i][1];

int weight = graph[i][2];

if (dis[x] != INT_MAX && dis[x] + weight < dis[y])

cout << "Graph contains negative weight cycle" << endl;

cout << "Vertex Distance from Source and sequence number" << endl;

for (int i = 0; i < V; i++)

if (dis[i] != INT_MAX)

cout << i << "\t\t" << dis[i] << "\t\t1" << endl;

else

cout << i << "\t\t"

<< "~"

<< "\t\t1" << endl;

int main()

int V = 5;

int E = 8;

int graph[][3] = {{0, 1, -1}, {0, 2, 4}, {1, 2, 3}, {1, 3, 2}, {1, 4, 2}, {3, 2, 5}, {3, 1, 1}, {4, 3, -3}};

cout << "\nRouting table for node 0" << endl;

BellmanFord(graph, V, E, 0);

cout << "\nRouting table for node 1" << endl;

BellmanFord(graph, V, E, 1);

cout << "\nRouting table for node 2" << endl;

BellmanFord(graph, V, E, 2);
cout << "\nRouting table for node 3" << endl;

BellmanFord(graph, V, E, 3);

cout << "\nRouting table for node 4" << endl;

BellmanFord(graph, V, E, 4);

return 0;

OUTPUT :

LEARNING OUTCOME :
• Cannot be implemented commercially or on a larger scale.
• Not suitable for many networks which are dynamic in nature. Slower protocol
processing time .
Experiment 7
AIM :
WAP to implement Dynamic Source Routing Protocol .

THEORY :
The Dynamic Source Routing protocol (DSR) is a simple and efficient routing protocol
designed specifically for use in multi-hop wireless ad hoc networks of mobile nodes.
DSR allows the network to be completely self-organizing and self-configuring without
needing any existing network infrastructure or administration.
It is a reactive protocol, and all aspects of the protocol operate entirely on-demand
basis. It works on the concept of source routing. Source routing is a routing technique
in which the sender of a packet determines the complete sequence of nodes through
which the packets are forwarded.
The advantage of source routing is: intermediate nodes do not need to maintain up-
to date routing information to route the packets they forward. The protocol
comprises the two main mechanisms of "Route Discovery" and "Route Maintenance."
DSR requires each node to maintain a route – cache of all known self–to–destination
pairs. If a node has a packet to send, it attempts to use this cache to deliver the
packet.
If the destination does not exist in the cache, then a route discovery phase is initiated
to discover a route to the destination by sending a route request. This request
includes the destination address, source address, and unique identification number. If
a route is available from the route – cache but is not valid anymore, a route
maintenance procedure may be initiated.
A node processes the route request packet only if it has not previously processed the
packet and its address is not present in the route cache. A route reply is generated by
the destination or by any of the intermediate nodes when it knows how to reach the
destination .

CODE :
#include <bits/stdc++.h>

using namespace std;

int minDistance(int dist[], bool sptSet[], int vertices)


{

int min_val = INT_MAX, min_id;

for (int v = 0; v < vertices; v++)

if (!sptSet[v] && dist[v] <= min_val)

min_val = dist[v], min_id = v;

return min_id;

void showPath(int from[], int dest, int src, int vertices)

int destination = dest;

cout << "\nThe RREP packet will be : ";

vector<int> path;

while (from[dest] != -1)

path.push_back(dest);

dest = from[dest];

path.push_back(dest);

cout << "\n\n";

cout << "From source = " << src << " to node " << destination << " : Path = ";

for (int i = path.size() - 1; i >= 0; i--)

if (i != 0)

cout << path[i] << "->";

else

cout << path[i];

cout << "\n";

void DSRRouting(int **graph, int source, int destination, int vertices)

{
int dist[vertices];

int from[vertices];

bool sptSet[vertices];

for (int i = 0; i < vertices; i++)

dist[i] = INT_MAX, sptSet[i] = false;

dist[source] = 0;

from[source] = -1;

for (int count = 0; count < vertices - 1; count++)

int u = minDistance(dist, sptSet, vertices);

sptSet[u] = true;

for (int v = 0; v < vertices; v++)

if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])

dist[v] = dist[u] + graph[u][v];

from[v] = u;

showPath(from, destination, source, vertices);

int main()

int vertices = 9;

// Allocate a double-pointer graph

int **graph_step = new int *[vertices];

for (int i = 0; i < vertices; i++)

graph_step[i] = new int[vertices];

// Initialize adjacency matrix

int temp_graph[9][9] = {
{1, 0, 1, 0, 1, 0, 0, 1, 0},

{1, 0, 1, 0, 1, 0, 0, 0, 1},

{0, 1, 0, 1, 1, 1, 1, 0, 0},

{0, 1, 1, 0, 1, 1, 0, 0, 1},

{1, 0, 0, 1, 0, 1, 0, 0, 0},

{0, 0, 1, 1, 1, 0, 1, 0, 1},

{0, 0, 0, 0, 0, 1, 0, 1, 0},

{1, 1, 1, 0, 0, 1, 0, 0, 1},

{0, 0, 1, 0, 0, 0, 0, 1, 1}};

for (int i = 0; i < vertices; i++)

for (int j = 0; j < vertices; j++)

graph_step[i][j] = temp_graph[i][j];

cout << "\n-> Graph view / Adjacency matrix:\n ";

for (int i = 0; i < vertices; i++)

cout << i << " ";

cout << "\n";

for (int i = 0; i < vertices; i++)

cout << i << " - ";

for (int j = 0; j < vertices; j++)

cout << graph_step[i][j] << " ";

cout << "\n";

int source_vertex, dest_vertex;

cout << "\nEnter source node : ";

cin >> source_vertex;

cout << "Enter destination node : ";

cin >> dest_vertex;


DSRRouting(graph_step, source_vertex, dest_vertex, vertices);

for (int i = 0; i < vertices; i++)

delete[] graph_step[i];

delete[] graph_step;

return 0;

OUTPUT :

LEARNING OUTCOME :
• Routers are maintained only between nodes That need to communicate. This
reduces the overhead of route maintenance.
• Route caching can further reduce route discovery overhead.
• A single route Discovery may yield routes to the destination due to
intermediate nodes replying from local caches.
• Stale caches will lead to increased overhead.
Experiment 8
AIM :
WAP to implement Leach Protocol.

THEORY :
Leach Protocol stands for Low Energy Adaptive Clustering Hierarchy. In Clustered
Network Architecture, Sensor Nodes autonomously clubs into groups called clusters.
It is based on the Leach Protocol which makes use of clusters.
Properties of Leach Protocol:
• It is a 2-tier hierarchy clustering architecture.
• It is a distributed algorithm for organizing the sensor nodes into groups called
clusters.
• The cluster head nodes in each of the autonomously formed clusters create the
Time-division multiple access (TDMA) schedules.
• It makes use of the concept called Data Fusion which makes it energy efficient.

Clustered Network Architecture is a very useful sensor network because of the


property of Data Fusion. Inside each cluster, each node communicates with the
cluster head to gather the information. All the clusters which are formed share their
gathered information to the base station. The cluster formation and selection of
cluster heads inside each cluster is an independent and autonomous distributed
process.

CODE :
#include <iostream>

#include <vector>

#include <string>

using namespace std;

#define Inf int(1e6);

int main()
{

int num_node;

cout << "Enter The Number Of nodes: " << flush;

cin >> num_node;

vector<vector<int>> graph_step(num_node, vector<int>(num_node));

cout << "Enter Adjency Matrix(I is inf)" << endl;

for (int i = 0; i < num_node; ++i)

for (int j = 0; j < num_node; ++j)

string graph_part;

cin >> graph_part;

graph_step[i][j] = Inf;

if (graph_part != "I")

graph_step[i][j] = stoi(graph_part);

cout << "Enter The Number of clusters: " << flush;

int num_clust;

cin >> num_clust;

vector<int> cluster_heading(num_clust);

cout << "Enter The Cluster heads :" << flush;

for (int i = 0; i < num_clust; ++i)

cin >> cluster_heading[i];

vector<vector<int>> clusters_group(num_clust);
for (int i = 0; i < num_clust; ++i)

cout << "Enter The members of cluster " << i + 1 << ": " << flush;

string x;

while (true)

cin >> x;

if (x == "N")

break;

clusters_group[i].push_back(stoi(x));

cout << "Enter the batteries of the nodes: " << flush;

vector<int> battery(num_node);

for (int i = 0; i < num_node; ++i)

cin >> battery[i];

cout << "Enter The Number of iterations: " << flush;

int num_iter;

cin >> num_iter;

// for every iteration

for (int i = 0; i < num_iter; ++i)

cout << "Iteration " << i + 1 << endl; // Pooling of new cluster head

for (int i = 0; i < num_clust; ++i)

int head = -1;

for (int node : clusters_group[i])

if (head == -1 or battery[node] > battery[head])


head = node;

cluster_heading[i] = head;

clusters_group[i].clear();

cout << "New Cluster Heads: " << flush;

for (int cluster_head : cluster_heading)

cout << "node" << cluster_head << " " << flush;

cout << endl;

for (int i = 0; i < num_node; ++i)

int nearest_cluster = -1;

for (int cluster = 0; cluster < num_clust; ++cluster)

if (nearest_cluster == -1 or graph_step[i][cluster_heading[cluster]] <


graph_step[i][cluster_heading[nearest_cluster]])

nearest_cluster = cluster;

clusters_group[nearest_cluster].push_back(i);

cout << "New clusters" << endl;

for (int i = 0; i < num_clust; ++i)

cout << "cluster" << i + 1 << ": " << flush;

for (int node : clusters_group[i])

cout << "node" << node << " " << flush;

cout << endl;

for (int i = 0; i < num_clust; ++i)

int cluster_head = cluster_heading[i];

battery[cluster_head] -= (int)clusters_group[i].size();

cout << "New battery levels: " << flush;

for (int bat_i : battery)


cout << bat_i << " " << flush;

cout << endl;

return 0;

OUTPUT :
Enter the number of nodes: 4

Enter Adjacency Matrix (Use 'I' for infinity):

124I

10 20 10 I

30 40 50 60

120 1 2 1

Enter the number of clusters: 2

Enter the cluster heads: 0 2

Enter the members of Cluster 1 (Enter 'N' to stop): 0 2 N

Enter the members of Cluster 2 (Enter 'N' to stop): 1 3 N

Enter the battery levels of the nodes:

Node 0: 100

Node 1: 50

Node 2: 75

Node 3: 95

Enter the number of iterations: 2

--- Iteration 1 ---

Recalculating Cluster Heads...

Current Cluster Heads:

Cluster 1: Node 0

Cluster 2: Node 3

Reassigning Nodes to Clusters...

Cluster Details:

Cluster 1: Node 0 Node 1 Node 2

Cluster 2: Node 3
Updating Battery Levels...

Battery Levels of All Nodes:

Node 0: 97

Node 1: 50

Node 2: 75

Node 3: 94

--- Iteration 2 ---

Recalculating Cluster Heads...

Current Cluster Heads:

Cluster 1: Node 0

Cluster 2: Node 3

Reassigning Nodes to Clusters...

Cluster Details:

Cluster 1: Node 0 Node 1 Node 2

Cluster 2: Node 3

Updating Battery Levels...

Battery Levels of All Nodes:

--- Final State ---

Current Cluster Heads:

Cluster 1: Node 0

Cluster 2: Node 3

Cluster 1: Node 0

Cluster 2: Node 3

Cluster Details:

Cluster 1: Node 0 Node 1 Node 2

Cluster 2: Node 3
Battery Levels of All Nodes:

Node 0: 94

Node 1: 50

Node 2: 75

Node 3: 93

You might also like