0% found this document useful (0 votes)
27 views

Assignment (2016 EE 384)

This document contains an assignment submission for a computer networks course. The assignment asks the student to implement and understand the Dijkstra's shortest path algorithm and Bellman-Ford algorithm. It provides documentation on how each algorithm works and includes Python code implementations of both algorithms on sample graph data. The student has submitted the assignment for grading.

Uploaded by

Nazish Khalid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Assignment (2016 EE 384)

This document contains an assignment submission for a computer networks course. The assignment asks the student to implement and understand the Dijkstra's shortest path algorithm and Bellman-Ford algorithm. It provides documentation on how each algorithm works and includes Python code implementations of both algorithms on sample graph data. The student has submitted the assignment for grading.

Uploaded by

Nazish Khalid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Computer Network Assignment

Electrical Engineering Department


UET Lahore (FSD Campus)

Submitted to
Course Code and Name Computer Networking

Assignment Number 1

Assignment Title Dijkstra’s Shortest Path Algorithm and Bellman–


Ford Algorithm implementation

Submitted by Nazish Khalid(2016-EE-384)

Date 1-july-2020

Mr. Azeem Iqbal

Reg. # 2016-EE-384

Marks 1
Computer Network Assignment

Assignment # 01

Dijkstra’s Shortest Path Algorithm and Bellman–Ford Algorithm implementation

Aim: the task is to understand the Dijkstra’s shortest path algorithm and bellman–ford algorithm
implementation

Dijkstra’s shortest path algorithm

Dijkstra’s algorithm finds a shortest path tree from a single source node, by building a set of nodes
that have minimum distance from the source.

The graph has the following:

 vertices, or nodes, denoted in the algorithm by vv or uu;


 weighted edges that connect two nodes: (u,vu,v) denotes an edge,
and w(u,v)w(u,v) denotes its weight. In the diagram on the right, the weight for each edge is
written in gray.
This is done by initializing three values:

 distdist, an array of distances from the source node ss to each node in the graph,
initialized the following way: distdist(ss) = 0; and for all other nodes vv, distdist(vv)
= \infty∞. This is done at the beginning because as the algorithm proceeds, the distdist from
the source to each node vv in the graph will be recalculated and finalized when the shortest
distance to vv is found

2
Computer Network Assignment
 QQ, a queue of all nodes in the graph. At the end of the algorithm's progress, QQ will be
empty.
 SS, an empty set, to indicate which nodes the algorithm has visited. At the end of the
algorithm's run, SS will contain all the nodes of the graph.
The algorithm proceeds as follows:

1. While QQ is not empty, pop the node vv, that is not already in SS, from QQ with the
smallest distdist (vv). In the first run, source node ss will be chosen because distdist(ss) was
initialized to 0. In the next run, the next node with the smallest distdist value is chosen.
2. Add node vv to SS, to indicate that vv has been visited
3. Update distdist values of adjacent nodes of the current node vv as follows: for each new
adjacent node uu,

 if distdist (vv) + weight(u,v)weight(u,v) < distdist (uu), there is a new minimal distance


found for uu, so update distdist (uu) to the new minimal distance value;
 otherwise, no updates are made to distdist (uu).
The algorithm has visited all nodes in the graph and found the smallest distance to each
node. Distdist now contains the shortest path tree from source ss.

THE ALGORITHM IMPLEMENTATION IN PYTHON

Code

class Graph:

# A utility function to find the


# vertex with minimum dist value, from
# the set of vertices still in queue
def minDistance(self,dist,queue):
# Initialize min value and min_index as -1
minimum = float("Inf")
min_index = -1
# from the dist array,pick one which
# has min value and is till in queue
for i in range(len(dist)):
if dist[i] < minimum and i in queue:
minimum = dist[i]
min_index = i
return min_index
# Function to print shortest path
# from source to j
# using parent array
def printPath(self, parent, j):

3
Computer Network Assignment
#Base Case : If j is source
if parent[j] == -1 :
print j,
return
self.printPath(parent , parent[j])
print j,
# A utility function to print
# the constructed distance
# array
def printSolution(self, dist, parent):
src = 0
print("Vertex \t\tDistance from Source\tPath")
for i in range(1, len(dist)):
print("\n%d --> %d \t\t%d \t\t\t\t\t" % (src, i, dist[i])),
self.printPath(parent,i)
'''Function that implements Dijkstra's single source shortest path algorithm for a graph represented using
adjacency matrix representation'''
def dijkstra(self, graph, src):

row = len(graph)
col = len(graph[0])

# The output array. dist[i] will hold


# the shortest distance from src to i
# Initialize all distances as INFINITE
dist = [float("Inf")] * row
#Parent array to store
# shortest path tree
parent = [-1] * row
# Distance of source vertex
# from itself is always 0
dist[src] = 0

# Add all vertices in queue


queue = []
for i in range(row):
queue.append(i)

#Find shortest path for all vertices


while queue:

# Pick the minimum dist vertex


# from the set of vertices
# still in queue
u = self.minDistance(dist,queue)
# remove min element
queue.remove(u)
4
Computer Network Assignment
# Update dist value and parent
# index of the adjacent vertices of
# the picked vertex. Consider only
# those vertices which are still in
# queue
for i in range(col):
''Update dist[i] only if it is in queue, there ian edge from u to i, and total weight of path from src to i
through u is smaller than current value of dist[i]'''
if graph[u][i] and i in queue:
if dist[u] + graph[u][i] < dist[i]:
dist[i] = dist[u] + graph[u][i]
parent[i] = u
# print the constructed distance array
self.printSolution(dist,parent)

g= Graph ()
graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
# Print the solution
g.dijkstra(graph,0)
Result

5
Computer Network Assignment
Bellman–Ford Algorithm implementation

The Bellman-Ford algorithm is an extension of Dijkstra’s algorithm which calculates the shortest


distance from the source point to all of the vertices. While Dijkstra’s algorithm just works for edges
with positive distances, the Bellman-Ford algorithm works for negative distances as well.

Algorithm

1. List down all the edges of the graph. This can be done easily if the graph is represented by
an adjacency list.

2. Calculate the number of iterations with “V - 1”. The number of iterations will be equal to
the number of vertices because the shortest distance to an edge can be adjusted V - 1 times
at maximum.

3. Start with an arbitrary vertex and assign it the minimum distance of zero. All other nodes
should be assigned infinity since we are exaggerating the actual distances.

4. In each iteration, update the distance for each edge if the new distance is smaller than the
one assigned before. The distance to each node will be the cumulative distance from the
starting node to this particular node.

5. We need to consider all the iterations to make sure that all possible paths are considered. If
we do this, we will end up with the shortest distance.

Implementation in python

Code

class Graph:
def __init__(self, vertices):
self.V = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges

# Add edges
def add_edge(self, s, d, w):
6
Computer Network Assignment
self.graph.append([s, d, w])

# Print the solution


def print_solution(self, dist):
print("Vertex Distance from Source")
for i in range(self.V):
print("{0}\t\t{1}".format(i, dist[i]))

def bellman_ford(self, src):

# Step 1: fill the distance array and predecessor array


dist = [float("Inf")] * self.V
# Mark the source vertex
dist[src] = 0

# Step 2: relax edges |V| - 1 times


for _ in range(self.V - 1):
for s, d, w in self.graph:
if dist[s] != float("Inf") and dist[s] + w < dist[d]:
dist[d] = dist[s] + w

# Step 3: detect negative cycle


# if value changes then we have a negative cycle in the graph
# and we cannot find the shortest distances
for s, d, w in self.graph:
if dist[s] != float("Inf") and dist[s] + w < dist[d]:
print("Graph contains negative weight cycle")
return

# No negative weight cycle found!


# Print the distance and predecessor array
self.print_solution(dist)
g = Graph(5)
g.add_edge(0, 1, 5)
g.add_edge(0, 2, 4)
g.add_edge(1, 3, 3)
g.add_edge(2, 1, 6)
g.add_edge(3, 2, 2)

g.bellman_ford(0)

7
Computer Network Assignment
Result

You might also like