Shortest Path Problem Between Routing Terminals – Implementation in Python
Last Updated :
27 Feb, 2020
The famous Dijkstra’s algorithm can be used in a variety of contexts – including as a means to find the shortest route between two routers, also known as Link state routing. This article explains a simulation of Dijkstra’s algorithm in which the nodes (routers) are terminals.
Once the shortest path between two nodes (terminals) is calculated, the shortest path itself is sent as a message to each terminal on its path in sequence, until the destination terminal is reached. Whenever the message has traversed a node, its terminal displays the traversal. In this way, it is possible to both see and simulate the passage of a message across a shortest calculated route.
The procedure to run the following code is as follows:
- Execute the driver code
- Before providing any input to the driver code, run the router codes router1.py, router2.py, etc. in separate terminals/tabs.
- Now provide input to the driver code in the form of a matrix G, in which any entry
G[i, j]
is the distance from node i to node j. The matrix must be symmetrical. If i=j, then D[i, j]=0
as the distance between a node and itself is considered to be nothing. If there is no direct connection between two nodes, then D[i, j]=999
(the equivalent of infinity).
- Specify source and destination nodes, where the nodes vary from 0 to 3, and represent terminals 1 to 4 respectively.
This implementation specifies four nodes but this can easily be extended to N nodes with N terminals and port numbers representing processes running on them respectively.
Consider the following example of a four-node network, with distances between them as specified and nodes numbered 0 to 3 from left to right:

Distances between terminals
For this network, the matrix G with entries G[i, j] as specified above would be:
[[0, 1, 999, 999],
[1, 0, 2, 999],
[999, 2, 0, 3],
[999, 999, 3, 0]]
This matrix would have to be input to the driver code. Dijkstra’s algorithm is used to find the shortest path between source and destination. A list containing the remaining path is sent to each node en route to the final destination.
The implementation in Python is specified below.
import socket
import sys
import pickle
S = set ()
G = []
for i in range ( 4 ):
listo = [ 0 , 0 , 0 , 0 ]
for j in range ( 4 ):
listo[j] = int ( input ( "give input" ))
G.append(listo)
source = int ( input ( "give source" ))
destination = int ( input ( "give destination" ))
Q = []
for i in range ( 4 ):
Q.append(i)
d = [ 0 , 0 , 0 , 0 ]
pi = [ 0 , 0 , 0 , 0 ]
for i in range ( 4 ):
if (i = = source):
d[i] = 0
else :
d[i] = 999
for i in range ( 4 ):
pi[i] = 9000
S.add(source)
while ( len (Q)! = 0 ):
x = min (d[q] for q in Q)
u = 0
for q in Q:
if (d[q] = = x):
u = q
print (u, "Is the minimum distance" )
Q.remove(u)
S.add(u)
adj = []
for y in range ( 4 ):
if (y ! = u and G[u][y]! = 999 ):
adj.append(y)
for v in adj:
if (d[v]>(d[u] + G[u][v])):
d[v] = d[u] + G[u][v]
pi[v] = u
route = []
x = destination
if (pi[x] = = 9000 ):
print (source)
else :
while (pi[x]! = 9000 ):
route.append(x)
x = pi[x]
route.reverse()
print (route)
print (pi)
print (d)
sendingroute = pickle.dumps(route)
sockets = [ 8895 , 8896 , 8897 , 8898 ]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((socket.gethostname(), sockets))
try :
sock.send(sendingroute)
finally :
print ("")
sock.close()
|
import socket
import sys
import pickle
for i in range ( 1 ) :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((socket.gethostname(), 8895 ))
sock.listen( 1 )
connection, client_address = sock.accept()
route = []
sockets = [ 8895 , 8896 , 8897 , 8898 ]
while 1 :
try :
route = pickle.loads(connection.recv( 1024 ))
except EOFError:
break
finally :
break
print ( "Traversed 1" )
socknext = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if ( len (route)> 0 ):
x = route[ 0 ]
route.remove(x)
dataroute = pickle.dumps(route)
socknext.connect((socket.gethostname(), sockets[x]))
try :
socknext.send(dataroute)
data = socknext.recv( 16 )
print (data)
finally :
print ("")
socknext.close()
|
import socket
import sys
import pickle
for i in range ( 1 ) :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((socket.gethostname(), 8896 ))
sock.listen( 1 )
connection, client_address = sock.accept()
route = []
sockets = [ 8895 , 8896 , 8897 , 8898 ]
while 1 :
try :
route = pickle.loads(connection.recv( 1024 ))
except EOFError:
break
finally :
break
print ( "Traversed 2" )
socknext = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if ( len (route)> 0 ):
x = route[ 0 ]
route.remove(x)
dataroute = pickle.dumps(route)
socknext.connect((socket.gethostname(), sockets[x]))
try :
socknext.send(dataroute)
data = socknext.recv( 16 )
print (data)
finally :
print ("")
socknext.close()
|
import socket
import sys
import pickle
for i in range ( 1 ) :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((socket.gethostname(), 8897 ))
sock.listen( 1 )
connection, client_address = sock.accept()
route = []
sockets = [ 8895 , 8896 , 8897 , 8898 ]
while 1 :
try :
route = pickle.loads(connection.recv( 1024 ))
except EOFError:
break
finally :
break
print ( "Traversed 3" )
socknext = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if ( len (route)> 0 ):
x = route[ 0 ]
route.remove(x)
dataroute = pickle.dumps(route)
socknext.connect((socket.gethostname(), sockets[x]))
try :
socknext.send(dataroute)
data = socknext.recv( 16 )
print (data)
finally :
print ("")
socknext.close()
|
import socket
import sys
import pickle
for i in range ( 1 ) :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((socket.gethostname(), 8898 ))
sock.listen( 1 )
connection, client_address = sock.accept()
route = []
sockets = [ 8895 , 8896 , 8897 , 8898 ]
while 1 :
try :
route = pickle.loads(connection.recv( 1024 ))
except EOFError:
break
finally :
break
print ( "Traversed 4" )
socknext = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if ( len (route)> 0 ):
x = route[ 0 ]
route.remove(x)
dataroute = pickle.dumps(route)
socknext.connect((socket.gethostname(), sockets[x]))
try :
socknext.send(dataroute)
data = socknext.recv( 16 )
print (data)
finally :
print ("")
socknext.close()
|

Dijkstra Output
Terminal Output –

Terminal Output
Similar Reads
Find Shortest Path Using Python OSMnx Routing Module
This article demonstrates how to use the OSMnx routing module to find the shortest path, illustrated with practical examples. Syntax of osmnx.routing.shortest_path() FunctionOSMnx routing module has the 'shortest_path' functionality to find the nearest path from the origin node to the destination no
3 min read
Find K Shortest Path Using OSMnx Routing Module in Python
OSMnx, a Python library built on top of OpenStreetMap data, offers a powerful set of tools for street network analysis. One common task in network analysis is finding the K shortest paths between two locations. In this article, we'll explore how to find the k-shortest path using OSMnx module in Pyth
3 min read
Difference between Distance vector routing and Link State routing
Routing is a process in computer networks which is used to find best path to transmit data packets from one node to another. Distance Vector Routing and Link State Routing are two most used dynamic routing algorithms. They both are a part of Intradomain routing which refer to routing of devices with
3 min read
Johnsonâs algorithm for All-pairs shortest paths | Implementation
Given a weighted Directed Graph where the weights may be negative, find the shortest path between every pair of vertices in the Graph using Johnson's Algorithm. The detailed explanation of Johnson's algorithm has already been discussed in the previous post. Refer Johnsonâs algorithm for All-pairs
12 min read
Probabilistic shortest path routing algorithm for optical networks
Data transfer operations is a crucial aspect in case of networking and routing. So efficient data transfer operations is a must need, with minimum hardware cost (Optical Cables, WDM Network components, Decoders, Multiplexers) and also in the minimum time possible. Thus, the need is to propose an alg
5 min read
Using Stacks to solve Desert Crossing Problem in Python
A man is using a compass to cross a desert, and he has been given specific directions for his task. Following directions is only permitted: "NORTH", "EAST", "WEST", and "SOUTH". However, the desert has very hot weather, and it would be advantageous if man could save energy. Thus, your task is to sim
5 min read
Time saved travelling in shortest route and shortest path through given city
Given a matrix mat[][] of size N * N, where mat[i][j] represents the time taken to reach from ith city to jth city. Also, given M queries in the form of three arrays S[], I[], and D[] representing source, intermediate, and destination respectively. The task is to find the time taken to go from S[i]
10 min read
Get trains between stations using Python
Suppose you want to travel using Indian railways and want to look for the trains between specified stations. Doing this manually can be very hectic. So in this article, we will write a script that will automatically fetch data from railyatri and will tell the name of the trains along with their code
3 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is
3 min read
Transportation Problem | Set 2 (NorthWest Corner Method)
An introduction to Transportation problem has been discussed in the previous article, in this article, finding the initial basic feasible solution using the NorthWest Corner Cell Method will be discussed. Explanation: Given three sources O1, O2 and O3 and four destinations D1, D2, D3 and D4. For the
7 min read