Module 3
Module 3
MODULE 3
NETWORK LAYER
INTRODUCTION:
The network Layer is the third layer in the OSI model of computer networks. Its main function
is to transfer network packets from the source to the destination. It involves both the source host
and the destination host.
these services are packetizing, routing, and forwarding.
In the 7-layer OSI model, the network layer is layer 3. The Internet Protocol (IP) is a key
protocol used at this layer, along with other protocols for routing, testing, and encryption.
Features of Network Layer
• The main responsibility of the Network layer is to carry the data packets from the source to
the destination without changing or using them.
• If the packets are too large for delivery, they are fragmented i.e., broken down into smaller
packets.
• It decides the route to be taken by the packets to travel from the source to the destination
among the multiple routes available in a network (also called routing).
• The source and destination addresses are added to the data packets inside the network layer.
Services Offered by Network Layer
The services which are offered by the network layer protocol are as follows:
• Packetizing
• Routing
• Forwarding
1. Packetizing
The process of encapsulating the data received from the upper layers of the network (also called
payload) in a network layer packet at the source and decapsulating the payload from the network
layer packet at the destination is known as packetizing.
The source host adds a header that contains the source and destination address and some other
relevant information required by the network layer protocol to the payload received from the
upper layer protocol and delivers the packet to the data link layer.
2.Routing
Routing is the process of moving data from one device to another device. These are two other
services offered by the network layer. In a network, there are a number of routes available from
the source to the destination. The network layer specifies some strategies which find out the best
possible route. This process is referred to as routing. There are a number of routing protocols
that are used in this process and they should be run to help the routers coordinate with each other
and help in establishing communication throughout the network
3.Forwarding
Forwarding is simply defined as the action applied by each router when a packet arrives at one
of its interfaces. When a router receives a packet from one of its attached networks, it needs to
forward the packet to another attached network (unicast routing) or to some attached networks
(in the case of multicast routing). Routers are used on the network for forwarding a packet from
the local network to the remote network. So, the process of routing involves packet forwarding
from an entry interface out to an exit interface.
Differences Between Routing and Forwarding
Routing Forwarding
IPv4 is 32-bit addressing scheme used as TCP/IP host addressing mechanism. IP addressing
enables every host on the TCP/IP network to be uniquely identifiable.
IPv4 provides hierarchical addressing scheme which enables it to divide the network into sub-
networks, each with well-defined number of hosts.
• Class A - it uses first octet for network addresses and last three octets for host addressing
• Class B - it uses first two octets for network addresses and last two for host addressing
• Class C - it uses first three octets for network addresses and last one for host addressing
.
Example: 192.168.1.1
Class D
Class D is used for multicast addressing and in a class D address the first octet would always
start with ‘1110’. Thus, class D addresses range from 224.0.0.0 to 239.255.255.255. Its Subnet
mask is not defined.
Example: 239.2.2.2
Class D addresses are used by routing protocols like OSPF, RIP, etc.
Class E
Class E addresses are reserved for research purposes and future use. The first octet in a class E
address starts with ‘1111’. Thus, class E addresses range from 240.0.0.0 to 255.255.255.255. Its
Subnet mask is not defined.
Disadvantage of Classful Addressing
• Class A with a mask of 255.0.0.0 can support 128 Network, 16,777,216 addresses per
network and a total of 2,147,483,648 addresses.
• Class B with a mask of 255.255.0.0 can support 16,384 Network, 65,536 addresses per
network and a total of 1,073,741,824 addresses.
• Class C with a mask of 255.255.255.0 can support 2,097,152 Network, 256 addresses per
network and a total of 536,870,912 addresses.
IPv4 also has well-defined address spaces to be used as private addresses (not routable on internet),
and public addresses (provided by ISPs and are routable on internet
• Network
• Host
Division of Address • Host
• Subnet
• Subnet
Exhaustion of IPv4 addresses gave birth to a next generation Internet Protocol version 6. IPv6
addresses its nodes with 128-bit wide address providing plenty of address space for future to be
used on entire planet or beyond.
IPv6 has introduced Anycast addressing but has removed the concept of broadcasting. IPv6
enables devices to self-acquire an IPv6 address and communicate within that subnet. This auto-
configuration removes the dependability of Dynamic Host Configuration Protocol (DHCP)
servers. This way, even if the DHCP server on that subnet is down, the hosts can communicate
with each other.
IPv6 provides new feature of IPv6 mobility. Mobile IPv6 equipped machines can roam around
without the need of changing their IP addresses.
IPv6 is still in transition phase and is expected to replace IPv4 completely in coming years. At
present, there are few networks which are running on IPv6. There are some transition mechanisms
available for IPv6 enabled networks to speak and roam around different networks easily on IPv4.
These are:
Internet Protocol is one of the major protocols in the TCP/IP protocols suite. This protocol works
at the network layer of the OSI model and at the Internet layer of the TCP/IP model. Thus this
protocol has the responsibility of identifying hosts based upon their logical addresses and to route
data among them over the underlying network.
IP provides a mechanism to uniquely identify hosts by an IP addressing scheme. IP uses best effort
delivery, i.e. it does not guarantee that packets would be delivered to the destined host, but it will
do its best to reach the destination. Internet Protocol version 4 uses 32-bit logical address.
Internet Protocol being a layer-3 protocol (OSI) takes data Segments from layer-4 (Transport) and
divides it into packets. IP packet encapsulates data unit received from above layer and add to its
own header information.
The encapsulated data is referred to as IP Payload. IP header contains all the necessary information
to deliver the packet at the other end.
needs to be identified
uniIP header includes many relevant information including Version Number, which, in this
context, is 4. Other details are as follows −
In this mode, data is sent only to one destined host. The Destination Address field contains 32- bit
IP address of the destination host. Here the client sends data to the targeted server −
This mode is a mix of the previous two modes, i.e. the packet sent is neither destined to a single
host nor all the hosts on the segment. In this packet, the Destination Address contains a special
address which starts with 224.x.x.x and can be entertained by more than one host.
Here a server sends packets which are entertained by more than one servers. Every network has
one IP address reserved for the Network Number which represents the network and one IP address
reserved for the Broadcast Address, which represents all the hosts in that network.
A single IP address can contain information about the network and its sub-network and ultimately
the host. This scheme enables the IP Address to be hierarchical where a network can have many
sub-networks which in turn can have many hosts.
**Subnetting**
The 32-bit IP address contains information about the host and its network. It is very necessary to
distinguish both. For this, routers use Subnet Mask, which is as long as the size of the network
address in the IP address. Subnet Mask is also 32 bits long. If the IP address in binary is ANDed
with its Subnet Mask, the result yields the Network address. For example, say the IP Address is
192.168.1.152 and the Subnet Mask is 255.255.255.0 then −
This way the Subnet Mask helps extract the Network ID and the Host from an IP Address. It can
be identified now that 192.168.1.0 is the Network number and 192.168.1.152 is the host on that
network.
Binary Representation
The positional value method is the simplest form of converting binary from decimal value. IP
address is 32 bit value which is divided into 4 octets. A binary octet contains 8 bits and the value
of each bit can be determined by the position of bit value '1' in the octet.
Positional value of bits is determined by 2 raised to power (position – 1), that is the value of a bit
1 at position 6 is 2^(6-1) that is 2^5 that is 32. The total value of the octet is determined by adding
up the positional value of bits. The value of 11000000 is 128+64 = 192. Some examples are shown
in the table below −
Drawback of IPv4
• Limited Address Space: IPv4 has a limited number of addresses, which is not enough for
the growing number of devices connecting to the internet.
• Complex Configuration: IPv4 often requires manual configuration or DHCP to assign
addresses, which can be time-consuming and prone to errors.
• Less Efficient Routing: The IPv4 header is more complex, which can slow down data
processing and routing.
• Security Issues: IPv4 does not have built-in security features, making it more vulnerable to
attacks unless extra security measures are added.
• Limited Support for Quality of Service (QoS): IPv4 has limited capabilities for
prioritizing certain types of data, which can affect the performance of real-time applications
like video streaming and VoIP.
• Fragmentation: IPv4 allows routers to fragment packets, which can lead to inefficiencies
and increased chances of data being lost or corrupted.
• Broadcasting Overhead: IPv4 uses broadcasting to communicate with multiple devices on
a network, which can create unnecessary network traffic and reduce performancerols the
congestion of data packets in the network.
• Inside local address – An IP address that is assigned to a host on the Inside (local)
network. The address is probably not an IP address assigned by the service provider i.e.,
these are private IP addresses. This is the inside host seen from the inside network.
• Inside global address – IP address that represents one or more inside local IP addresses to
the outside world. This is the inside host as seen from the outside network.
• Outside local address – This is the actual IP address of the destination host in the local
network after translation.
• Outside global address – This is the outside host as seen from the outside network. It is
the IP address of the outside destination host before translation.
1. Static NAT – In this, a single unregistered (Private) IP address is mapped with a legally
registered (Public) IP address i.e one-to-one mapping between local and global addresses.
This is generally used for Web hosting. These are not used in organizations as there are
many devices that will need Internet access and to provide Internet access, a public IP
address is needed.
Suppose, if there are 3000 devices that need access to the Internet, the organization has to
buy 3000 public addresses that will be very costly.
3. Port Address Translation (PAT) – This is also known as NAT overload. In this, many
local (private) IP addresses can be translated to a single registered IP address. Port numbers
are used to distinguish the traffic i.e., which traffic belongs to which IP address. This is
most frequently used as it is cost-effective as thousands of users can be connected to the
Internet by using only one real global (public) IP address.
Advantages of NAT –
• It provides privacy as the device’s IP address, sending and receiving the traffic, will be
hidden.
Disadvantage of NAT –
• Also, the router being a network layer device, should not tamper with port
numbers(transport layer) but it has to do so because of NAT.
Provider Id: Depending on the number of service providers that operate under a region, certain
bits will be allocated to the Provider Id field.
Subscriber Id: After Provider Id is fixed, the remaining part can be used by ISP as a normal IP
address.
Intra Subscriber: This part can be modified as per the need of the organization that is using the
service
Global Routing Prefix: Global routing prefix contains all the details of Latitude and Longitude.
In Geography-based Unicast address routing will be based on location.
Interface Id: In IPv6, instead of using Host Id, we use the term Interface Id.
Local Unicast
Addresses
These are of two types: Link-local and Site-Local
1. Link-Local Address
A link-local address is used for addressing a single link. It can also be used to communicate with
nodes on the same link. The link-local address always begins with 1111111010 (i.e. FE80). The
router will not forward any packet with Link-local address.
2. Site Local Address
Site local addresses are equivalent to a private IP address in IPv4. Likely, some address space is
reserved, which can only be routed within an organization. The first 10-bits are set to 1111111011,
which is why Site local addresses always begin with FEC0. The following 32 bits are Subnet IDs,
which can be used to create a subnet within the organization. The node address is used to uniquely
identify the link; therefore, we use a 48-bits MAC address here.
**Advantages of IPv6**
1. Realtime Data Transmission : Realtime data transmission refers to the process of
transmitting data in a very fast manner or immediately. Example : Live streaming services
such as cricket matches, or other tournament that are streamed on web exactly as soon as it
happens with a maximum delay of 5-6 seconds.
• 2. IPv6 supports authentication: Verifying that the data received by the receiver from the
sender is exactly what the sender sent and came through the sender only not from any third
party. Example : Matching the hash value of both the messages for verification is also done by
IPv6.
• 3. IPv6 performs Encryption: Ipv6 can encrypt the message at network layer even if the
protocols of application layer at user level didn’t encrypt the message which is a major
advantage as it takes care of encryption.
• 4. Faster processing at Router: Routers are able to process data packets of Ipv6 much faster
due to smaller Base header of fixed size – 40 bytes which helps in decreasing processing time
resulting in more efficient packet transmission. Whereas in Ipv4, we have to calculate the
length of header which lies between 20-60 bytes.
Disadvantages of IPV6
• Transition Period: Due to widespread use of IPv4, shifting completely to IPv6 will take a
long time.
• Communication Barrier: IPv4 and IPv6 machines cannot communicate directly with each
other.
• No Backward Compatibility: IPv6 cannot run on IPv4-capable computers because it’s not
supported by IPv4 systems.
• Conversion Challenges: IPv6’s inability to uniquely identify each device on the network
makes the transition from IPv4 time-consuming.
• Protocol Isolation: IPv4 and IPv6 cannot communicate with each other directly, preventing
cross-protocol communication
IPv4 IPv6
IPv4 has a 32-bit address length IPv6 has a 128-bit address length
IPv4 IPv6
It can generate 4.29×109 address The address space of IPv6 is quite large it can
space produce 3.4×1038 address space
The Security feature is dependent on IPSEC is an inbuilt security feature in the IPv6
the application protocol
In IPv4 Packet flow identification is In IPv6 packet flow identification are Available and
not available uses the flow label field in the header
IPv4 can be converted to IPv6 Not all IPv6 can be converted to IPv4
IPv4 consists of 4 fields which are IPv6 consists of 8 fields, which are separated by a
separated by addresses dot (.) colon (:)
Example of IPv6:
Example of IPv4: 66.94.29.13
2001:0000:3238:DFE1:0063:0000:0000:FEFB
**Benefits of IPv6 over IPv4**
The recent Version of IP IPv6 has a greater advantage over IPv4. Here are some of the mentioned
benefits:
• Larger Address Space: IPv6 has a greater address space than IPv4, which is required for
expanding the IP Connected Devices. IPv6 has 128 bit IP Address rather and IPv4 has a 32-
bit Address.
• Improved Security: IPv6 has some improved security which is built in with it. IPv6 offers
security like Data Authentication, Data Encryption, etc. Here, an Internet Connection is more
Secure.
• Simplified Header Format: As compared to IPv4, IPv6 has a simpler and more effective
header Structure, which is more cost-effective and also increases the speed of Internet
Connection.
• Prioritize: IPv6 contains stronger and more reliable support for QoS features, which helps
in increasing traffic over websites and increases audio and video quality on pages.
• Improved Support for Mobile Devices: IPv6 has increased and better support for Mobile
Devices. It helps in making quick connections over other Mobile Devices and in a safer way
than IPv4.
Distance vector routing is a routing protocol that uses distance as a metric to determine the best
path between two nodes. It is also known as the Bellman-Ford algorithm.
Distance vector routing is used in simple network topologies where the number of hops between
two nodes is the primary metric used to determine the best path. In more complex network
topologies, other factors such as link bandwidth and latency can be taken into account when
determining the best path.
Advantages of Distance Vector Routing Algorithm
There major advantages to the distance vector routing algorithm are as follows:
• Distance vector routing is a routing protocol that uses the shortest path to a destination as
its primary criterion. This algorithm is used in local-area networks, metropolitan-area
networks, and wide-area networks.
• The main advantage of this algorithm is that it is easy to implement and does not require
many resources.
• Additionally, distance vector routing converges quickly; it means that it can find an optimal
route to a destination quickly after a change in network conditions.
There are a few disadvantages to the distance vector routing algorithm, as detailed below:
• First, it is not very scalable. This algorithm doesn’t work well in large networks because
the amount of information that needs to be exchanged between nodes can become too great.
• Additionally, this algorithm can suffer from routing loops. This occurs when there is a
change in the network, and incorrect information is propagated between nodes, causing a
loop.
• Also, this algorithm can be slow to converge on a new route after a change in the network.
There are a number of different applications for the Distance Vector Routing Algorithm. One
common application is in computer networking, specifically in routing data packets. This
algorithm is also used in some types of telephone switching systems. Additionally, it has been used
in military applications to route missiles.
•
• Routing Protocols
A routing protocol is a set of policies or algorithms routers use to exchange information about the
networks they are connected to. This information helps routers decide the best route to transmit
packets to their destination. Routing protocols function on the network layer of the OSI reference
model and use route update packets to communicate with each other.
Routers run various routing protocols to exchange updates and assist in finding the best paths to a
destination in a network. When a new network is added, routing protocols can learn about it and
recognize when a network is unavailable.
We now have a basic understanding of what routing protocols really are. Let’s move on to the
types of routing protocols.
Static Routing
In static routing, the routes are manually configured by means of the network administrator and do
not change based on network conditions. This type of routing is simple, stable, and rapid, but it
isn’t scalable or adaptable to network modifications. Static routing is best suited for small networks
with a fixed topology.
Dynamic Routing
In dynamic routing, the routes are automatically updated based on modifications inside the
network topology or metrics, including hop count number, bandwidth, delay, and so on. This sort
of routing is complex and efficient, but it consumes greater resources and bandwidth. Dynamic
routing is best suited for big, complicated networks with a variable topology.
Examples of Routing Protocols
Below, we have discussed various examples of routing protocols with their characteristics.
• RIP: Routing Information Protocol is a distance vector IGP that uses hop count as its
metric. It is one of the oldest and is also known to be the simplest routing protocol. Still, it
has many limitations, which include a maximum hop count of 15, slow convergence, and
high bandwidth consumption.
• EIGRP: Enhanced Interior Gateway Routing Protocol is a distance vector IGP that uses a
composite metric based totally on bandwidth, delay, reliability, load, and MTU. It is a
Cisco proprietary protocol that improves upon RIP with the aid of the usage of capabilities
that include partial updates, triggered updates, hello packets, and a DUAL set of rules or
algorithms.
• OSPF: Open Shortest Path First is a link state IGP that makes use of cost as its metric. It
is an open standard protocol that uses functions including areas, LSAs, SPF rules or
algorithms, DR/BDR election, and authentication. It has fast convergence, low bandwidth
intake, and high scalability.
• BGP: Border Gateway Protocol is a path vector EGP that uses attributes that include AS
path, next hop, MED, origin, and community to pick the best routes. It is an open standard
protocol that is used to change routing information among ASes on the Internet. It has slow
convergence, high CPU intake, and complex configuration.
• IS-IS: Intermediate System to Intermediate System is a link state IGP/EGP that uses cost
as its metric. It is an ISO standard protocol that makes use of features such as areas, LSPs,
SPF set of rules, DIS election, and authentication. It has fast convergence, low bandwidth
consumption, and high scalability.
• They make it possible for routers to automatically and dynamically learn about distant
networks.
• By locating alternative channels, they let routers adjust to network changes and outages.
• By choosing the optimum path based on multiple variables, they enhance network
performance.
• By doing away with manual route setting, they lower administrative burden.
• Routing protocols can lead to routing loops and sometimes inconsistency if not configured
properly.
• Complexity and security issues in the network design are some of the drawbacks that
routing protocols can generate.
• Sometimes, compatibility issues arise because different versions of routing protocols are
used for different purposes.
Below, we have compared Routing Protocol vs Routed Protocol in a tabular form to explain the
difference between the two.
Example RIP, EIGRP, OSPF, BGP, etc. IP, IPX, AppleTalk, etc.
These are the main differences between Routing and Routed Protocols. In summary, routed
protocols deal with the content and structure of data packets, while routing protocols deal with the
rules and algorithms that routers use to decide how to forward these data packets from one network
segment to another. Routing protocols ensure that data packets from one network can traverse
multiple networks to reach their destination by determining the most efficient path.
• Centralized: In this method, a centralized node has entire information about the network
and makes all the routing decisions. The advantage of this is only one node is required to
keep the information of the entire network and the disadvantage is that if the central node
goes down the entire network is done.
• Distributed: In this method, the node receives information from its neighbors and then
takes the decision about routing the packets. A disadvantage is that the packet may be delayed
if there is a change in between intervals in which it receives information and sends packets.
It is also known as a decentralized algorithm as it computes the least-cost path between
source and destination.
2. Non-Adaptive Algorithms
These are the algorithms that do not change their routing decisions once they have been selected.
This is also known as static routing as a route to be taken is computed in advance and
downloaded to routers when a router is booted.
Further, these are classified as follows:
• Flooding: This adapts the technique in which every incoming packet is sent on every
outgoing line except from which it arrived. One problem with this is that packets may go in
a loop and as a result of which a node may receive duplicate packets. These problems can be
overcome with the help of sequence numbers, hop count, and spanning trees.
• Random walk: In this method, packets are sent host by host or node by node to one of its
neighbors randomly. This is a highly robust method that is usually implemented by sending
packets onto the link which is least queued.
Random Walk
3. Hybrid Algorithms
As the name suggests, these algorithms are a combination of both adaptive and non-adaptive
algorithms. algorithm.
Further, these are classified as follows:
• Link-state: In this method, each router creates a detailed and complete map of the network
which is then shared with all other routers. This allows for more accurate and efficient routing
decisions to be made.
• Distance vector: In this method, each router maintains a table that contains information
about the distance and direction to every other node in the network. This table is then shared
with other routers in the network. The disadvantage of this method is that it may lead to
routing loops
Introduction to Graphs
Graphs are non-linear data structures representing the "connections" between the elements. These
elements are known as the Vertices, and the lines or arcs that connect any two vertices in the graph
are known as the Edges. More formally, a Graph comprises a set of Vertices (V) and a set of
Edges (E). The Graph is denoted by G(V, E).
Components of a Graph
1. Vertices: Vertices are the basic units of the graph used to represent real-life objects,
persons, or entities. Sometimes, vertices are also known as Nodes.
2. Edges:Edges are drawn or used to connect two vertices of the graph. Sometimes, edges are
also known as Arcs.
In the above figure, the Vertices/Nodes are denoted with Colored Circles, and the Edges are
denoted with the lines connecting the nodes.
Types of Graphs
1. Undirected Graph
2. Directed Graph
Undirected Graph: A Graph with edges that do not have a direction is termed an Undirected
Graph. The edges of this graph imply a two-way relationship in which each edge can be traversed
in both directions. The following figure displays a simple undirected graph with four nodes and
five edges.
Directed Graph: A Graph with edges with direction is termed a Directed Graph. The edges of
this graph imply a one-way relationship in which each edge can only be traversed in a single
direction. The following figure displays a simple directed graph with four nodes and five edges.
The absolute length, position, or orientation of the edges in a graph illustration characteristically
does not have meaning. In other words, we can visualize the same graph in different ways by
rearranging the vertices or distorting the edges if the underlying structure of the graph does not
alter.
Weighted Graphs
A Graph is said to be Weighted if each edge is assigned a 'weight'. The weight of an edge can
denote distance, time, or anything that models the 'connection' between the pair of vertices it
connects.
Weighted Graph
Dijkstra's Algorithm
• Dijkstra's algorithm finds the shortest path from one vertex to all other vertices.It does so
by repeatedly selecting the nearest unvisited vertex and calculating the distance to all the
unvisited neighbouring vertices.
• Dijkstra's algorithm is used for solving single-source shortest path problems for directed
or undirected paths. Single-source means that one vertex is chosen to be the start, and the
algorithm will find the shortest path from that vertex to all other vertices.
• Dijkstra's algorithm does not work for graphs with negative edges. For graphs with
negative edges, the Bellman-Ford algorithm that is described on the next page, can be used
instead.
• To find the shortest path, Dijkstra's algorithm needs to know which vertex is the source, it
needs a way to mark vertices as visited, and it needs an overview of the current shortest
distance to each vertex as it works its way through the graph, updating these distances when
a shorter distance is found.
It is a type of Greedy Algorithm that only works on Weighted Graphs having positive weights.
The time complexity of Dijkstra's Algorithm is O(V2) with the help of the adjacency matrix
representation of the graph. This time complexity can be reduced to O((V + E) log V) with the
help of an adjacency list representation of the graph, where V is the number of vertices and E is
the number of edges in the graph.
1. Dijkstra's Algorithm begins at the node we select (the source node), and it examines the
graph to find the shortest path between that node and all the other nodes in the graph.
2. The Algorithm keeps records of the presently acknowledged shortest distance from each
node to the source node, and it updates these values if it finds any shorter path.
3. Once the Algorithm has retrieved the shortest path between the source and another node,
that node is marked as 'visited' and included in the path.
4. The procedure continues until all the nodes in the graph have been included in the path. In
this manner, we have a path connecting the source node to all other nodes, following the
shortest possible path to reach each node.
A graph and source vertex are requirements for Dijkstra's Algorithm. This Algorithm is
established on Greedy Approach and thus finds the locally optimal choice (local minima in this
case) at each step of the Algorithm.
Each Vertex in this Algorithm will have two properties defined for it:
1. Visited Property
2. Path Property
Visited Property:
1. The 'visited' property signifies whether or not the node has been visited.
2. We are using this property so that we do not revisit any node.
3. A node is marked visited only when the shortest path has been found.
Path Property:
1. The 'path' property stores the value of the current minimum path to the node.
2. The current minimum path implies the shortest way we have reached this node till now.
3. This property is revised when any neighbor of the node is visited.
4. This property is significant because it will store the final answer for each node.
Initially, we mark all the vertices, or nodes, unvisited as they have yet to be visited. The path to all
the nodes is also set to infinity apart from the source node. Moreover, the path to the source node
is set to zero (0).
We then select the source node and mark it as visited. After that, we access all the neighbouring
nodes of the source node and perform relaxation on every node. Relaxation is the process of
lowering the cost of reaching a node with the help of another node.
In the process of relaxation, the path of each node is revised to the minimum value amongst the
node's current path, the sum of the path to the previous node, and the path from the previous node
to the current node.
Let us suppose that p[n] is the value of the current path for node n, p[m] is the value of the path up
to the previously visited node m, and w is the weight of the edge between the current node and
previously visited one (edge weight between n and m).
We then mark an unvisited node with the least path as visited in every subsequent step and update
its neighbor's paths.
We repeat this procedure until all the nodes in the graph are marked visited.
Whenever we add a node to the visited set, the path to all its neighboring nodes also changes
accordingly.
If any node is left unreachable (disconnected component), its path remains 'infinity'. In case the
source itself is a separate component, then the path to all other nodes remains 'infinity'.
The following is the step that we will follow to implement Dijkstra's Algorithm:
Step 1: First, we will mark the source node with a current distance of 0 and set the rest of the nodes
to INFINITY.
Step 2: We will then set the unvisited node with the smallest current distance as the current node,
suppose X.
Step 3: For each neighbor N of the current node X: We will then add the current distance of X
with the weight of the edge joining X-N. If it is smaller than the current distance of N, set it as the
new current distance of N.
Step 5: We will repeat the process from 'Step 2' if there is any node unvisited left in the graph.
Let us now understand the implementation of the algorithm with the help of an example:
Graph
1. We will use the above graph as the input, with node A as the source.
2. First, we will mark all the nodes as unvisited.
3. We will set the path to 0 at node A and INFINITY for all the other nodes.
4. We will now mark source node A as visited and access its neighboring nodes.
Note: We have only accessed the neighboring nodes, not visited them.
5. We will now update the path to node B by 4 with the help of relaxation because the path to
node A is 0 and the path from node A to B is 4, and the minimum((0 + 4),
INFINITY) is 4.
6. We will also update the path to node C by 5 with the help of relaxation because the path to
node A is 0 and the path from node A to C is 5, and the minimum((0 + 5),
INFINITY) is 5. Both the neighbors of node A are now relaxed; therefore, we can move
ahead.
7. We will now select the next unvisited node with the least path and visit it. Hence, we will
visit node B and perform relaxation on its unvisited neighbors. After performing
relaxation, the path to node C will remain 5, whereas the path to node E will become 11,
and the path to node D will become 13.
8. We will now visit node E and perform relaxation on its neighboring nodes B, D, and F.
Since only node F is unvisited, it will be relaxed. Thus, the path to node B will remain as
it is, i.e., 4, the path to node D will also remain 13, and the path to node F will become 14
(8 + 6).
9. Now we will visit node D, and only node F will be relaxed. However, the path to
node F will remain unchanged, i.e., 14.
10. Since only node F is remaining, we will visit it but not perform any relaxation as all its
neighboring nodes are already visited.
11. Once all the nodes of the graphs are visited, the program will end.
1. A = 0
2. B = 4 (A -> B)
3. C = 5 (A -> C)
4. D = 4 + 9 = 13 (A -> B -> D)
5. E = 5 + 3 = 8 (A -> C -> E)
6. F = 5 + 3 + 6 = 14 (A -> C -> E -> F)