You are on page 1of 74

Data Structure & Algorithms

(DSA) : CCT203
Semester - III, B.Tech. CSE (Cyber Security)
UNIT VI
GC Code: dyb4gii
Course Objectives
1. CO1: To impart to students the basic concepts of data structures and algorithms.
2. CO2: To familiarize students on different searching and sorting techniques.
3. CO3: To prepare students to use linear (stacks, queues, linked lists) and nonlinear (trees, graphs)
data structures.
4. CO4: To enable students to devise algorithms for solving real-world problems.
Text Books & Reference Books
Text Books:
1. Ellis Horowitz, Sartaj Sahni & Susan Anderson-Freed, Fundamentals of Data Structures in C,
Second Edition, Universities Press, 2008.
2. Mark Allen Weiss; Data Structures and Algorithm Analysis in C; Second Edition; Pearson
Education; 2002.
3. G.A.V. Pai; Data Structures and Algorithms: Concepts, Techniques and Application; First Edition;
McGraw Hill; 2008.
Reference Books:
1. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein; Introduction to
Algorithms; Third Edition; PHI Learning; 2009.
2. Ellis Horowitz, Sartaj Sahni and Sanguthevar Rajasekaran; Fundamentals of Computer
Algorithms; Second Edition; Universities Press; 2008.
3. A. K. Sharma; Data Structures using C, Second Edition, Pearson Education, 2013.
Course Outcomes
On completion of the course the student will be able to

1. Recognize different ADTs and their operations and specify their complexities.
2. Design and realize linear data structures (stacks, queues, linked lists) and analyze their
computation complexity.
3. Devise different sorting (comparison based, divide-and-conquer, distributive, and tree-based) and
searching (linear, binary) methods and analyze their time and space requirements.
4. Design traversal and path finding algorithms for Trees and Graphs.
UNIT VI Graphs and Hashing
Graphs:

● basic terminologies, representation of graphs, traversals (DFS, BFS) with complexity analysis,
● path finding (Dijkstra's SSSP, Floyd's APSP), and
● spanning tree (Prim's method, kruskal’s method) algorithms

Hashing:

● Hash functions and hash tables,


● closed and open hashing,
● randomization methods (division method, mid-square method, folding),
● collision resolution techniques.
Graphs: Introduction
● Non-linear data structure called graphs
● It is basically a collection of vertices (also called nodes) and edges that connect these vertices.
● It is a generalization of the tree structure
where, instead of having a purely parent-to-child relationship between tree nodes,
any kind of complex relationship can exist.

Why graphs are useful?

● Family trees: in which the member nodes have an edge from parent to each of their children.
● Transportation networks: in which nodes are airports, intersections, ports, etc.
The edges can be airline flights, one-way roads, shipping routes, etc
● Two types: Undirected Graphs & Directed Graphs
Graphs: Definition
Definition:
● A graph G is defined as an ordered set (V, E), where
V(G) represents the set of vertices and
E(G) represents the edges that connect these vertices.
● Figure shows a graph with
V(G) = {A, B, C, D and E} and
E(G) = {(A, B), (B, C), (A, D), (B, D), (D, E), (C, E)}.
● Note that there are five vertices or nodes and six edges in the graph.
Look at second figure which shows a directed graph.
● In a directed graph, edges form an ordered pair.
● If there is an edge from A to B, then there is a path from A to B
but not from B to A.
● The edge (A, B) is said to initiate from node A (also known as initial node)
and terminate at node B (terminal node).
Graphs: Basic Terminologies
● Adjacent nodes or neighbours:
For every edge, e = (u, v) that connects nodes u and v, the nodes u and v are the end-points and are
said to be the adjacent nodes or neighbours.
● Degree of a node:
Degree of a node u, deg(u), is the total number of edges containing the node u.
If deg(u) = 0, it means that u does not belong to any edge and such a node is known as an isolated
node.
● Regular graph:
It is a graph where each vertex has the same number
of neighbours. That is, every node has the same
degree. A regular graph with vertices of degree k is
called a k–regular graph or a regular graph of degree k.
Graphs: Basic Terminologies
● Path:
A path P written as P = {v0 , v1, v2, ..., vn), of length n from a node u to v is defined as a sequence
of (n+1) nodes. Here, u = v0 , v = vn and vi–1 is adjacent to vi for i = 1, 2, 3, ..., .
● Cycle:
A path in which the first and the last vertices are same. A simple cycle has no repeated edges or
vertices (except the first and last vertices).
● Connected graph:
If for any two vertices (u, v) in V there is a path from u to v.
That is to say that there are no isolated nodes in a connected
graph. A connected graph that does not have any cycle is
called a tree. Therefore, a tree is treated as a special graph
● Complete graph:
A graph G is said to be complete if all its nodes are fully connected. That is, there is a path from
one node to every other node in the graph. A complete graph has n(n–1)/2 edges, where n is the
number of nodes in G
Graphs: Basic Terminologies
● Labelled graph or weighted graph:
A graph is said to be labelled if every edge in the graph is assigned some data. In a weighted
graph, the edges of the graph are assigned some weight or length. The weight of an edge denoted
by w(e) is a positive value which indicates the cost of traversing the edge.
● Multiple edges:
Distinct edges which connect the same end-points are called multiple edges.
That is, e = (u, v) and e' = (u, v) are known as multiple edges of G
● Multi-graph:
A graph with multiple edges and/or loops is called a multi-graph.
● Size of a graph:
The size of a graph is the total number of edges in it.
Graphs: Representation of Graphs
There are three common ways of storing graphs in the computer’s memory.

They are:

● Adjacency matrix:
Sequential representation
● Linked representation:
by using an adjacency list that stores the neighbours of a node using a linked list.
● Adjacency multi-list:
which is an extension of linked representation.
Graphs: Adjacency Matrix representation
● For any graph G, having n nodes, the adjacency matrix will have the dimension of n x n.
● In an adjacency matrix, the rows and columns are labelled by graph vertices
● Since an adjacency matrix contains only 0s and 1s, it is called a bit matrix or a Boolean matrix
● A change in the order of nodes will result in a different adjacency matrix
Graphs: Adjacency Matrix representation
Conclusions:
● For a simple graph (that has no loops), the adjacency matrix has 0s on the diagonal.
● The adjacency matrix of an undirected graph is symmetric.
● The memory use of an adjacency matrix is O(n2), where n is the number of nodes in the graph.
● Number of 1s (or non-zero entries) in an adjacency matrix is equal to the number of edges n the
graph.
● The adjacency matrix for a weighted graph contains the weights of the edges connecting the nodes
Graphs: Powers of an adjacency matrix

● Every entry in the ith row and jth column of An


(where n is the number of nodes in the graph)
gives the number of paths of length n from
node vi to vj
Graphs: Adjacency List Representation
● easy to follow
● clearly shows the adjacent nodes of a
particular node
● preferred for representing sparse graphs in the
computer’s memory
● Adding new nodes in an adjacency matrix is a
difficult task, as the size of the matrix needs to
be changed and existing nodes may have to be
reordered
● Adding new nodes in G is easy and
straightforward when G is represented using
an adjacency list
Write a program to create a graph of n vertices
using an adjacency list. Also write the
code to read and print its information and
finally to delete the graph.
struct node{ void createGraph(struct node *Adj[], int
char vertex; no_of_nodes){
struct node *next; struct node *new_node, *last;
}; int i, j, n, val;
for(i = 0; i < no_of_nodes; i++) {
void main() { last = NULL;
struct node *Adj[10]; printf("\n Enter the number of neighbours of %d: ", i);
int i, no_of_nodes; scanf("%d", &n);
printf("\n Enter the number of nodes in G: for(j = 1; j <= n; j++) {
"); printf("\n Enter the neighbour %d of %d: ", j, i);
scanf("%d", &no_of_nodes); scanf("%d", &val);
new_node = (struct node *) malloc(sizeof(struct
for(i = 0; i < no_of_nodes; i++) node));
Adj[i] = NULL; new_node –> vertex = val;
new_node –> next = NULL;
createGraph(Adj, no_of_nodes); if (Adj[i] == NULL)
printf("\n The graph is: "); Adj[i] = new_node;
else
displayGraph(Adj, no_of_nodes); last –> next = new_node;
deleteGraph(Adj, no_of_nodes); last = new_node
void displayGraph (struct node *Adj[], int void deleteGraph (struct node *Adj[], int no_of_nodes) {
no_of_nodes) { int i;
struct node *ptr; struct node *temp, *ptr;
int i;
for(i = 0; i <= no_of_nodes; i++) {
for(i = 0; i < no_of_nodes; i++) { ptr = Adj[i];
ptr = Adj[i];
while(ptr ! = NULL) {
printf("\n The neighbours of node %d are:", i); temp = ptr;
ptr = ptr –> next;
while(ptr != NULL) { free(temp);
printf("\t%d", ptr –> vertex); }
ptr = ptr –> next;
} Adj[i] = NULL;
} }
} }
GRAPH TRAVERSAL ALGORITHMS
Graphs: Traversal (BFS and DFS)
● Travelling a graph means that one visits the vertices of a graph at least once.
● While breadth-first search uses a queue as an auxiliary data structure to store nodes for further
processing, the depth-first search scheme uses a stack.
● But both these algorithms make use of a variable STATUS.
● During the execution of the algorithm, every node in the graph will have the variable STATUS set
to 1 or 2, depending on its current state.
Breadth-First Search Algorithm
Graphs: BFS
● Breadth-first search (BFS) is a graph
search algorithm
● Begins at the root node and explores all
the neighbouring nodes.
● Then for each of those nearest nodes, the
algorithm explores their unexplored
neighbour nodes, and so on, until it finds
the goal
● This is accomplished by using a queue
that will hold the nodes that are waiting
for further processing and a variable
STATUS to represent the current state of
the node
Graphs: BFS Traversal

https://www.cs.usfca.edu/~galles/visualization/BFS.html
Graphs: BFS Traversal

https://www.cs.usfca.edu/~galles/visualization/BFS.html
Graphs: BFS Traversal
1. Take a Start node
a. Put it in a Queue & Visited = NULL
2. Queue is NOT EMPTY
a. Enqueue the neighbouring nodes
b. Dequeue the node and print the node and mark as visited.
3. Repeat the steps until Queue is EMPTY
● Start node = 0
● Queue = 0 and Visited =NULL
● Enqueue neighbouring nodes of 0,
Queue = 0, 1, 3, 4 and Dequeue the Queue = 0 and print = 0
Queue = 1, 3, 4 , Visited = 0
● Enqueue neighbouring nodes of 1,
Queue = 1, 3, 4, 2, 6 and Dequeue the Queue = 1 and print = 1
Queue = 3, 4, 2, 6
Graphs: BFS Traversal
1. Take a Start node
a. Put it in a Queue & Visited = NULL
2. Queue is NOT EMPTY
a. Enqueue the neighbouring nodes
b. Dequeue the node and print the node and mark as visited.
3. Repeat the steps until Queue is EMPTY
● Enqueue neighbouring nodes of 3,
Queue = 3, 4, 2, 6 , 5, 7 and Dequeue the Queue = 3 and print = 3
Queue = 4, 2, 6 , 5, 7
● Enqueue neighbouring nodes of 4,
Queue = 4, 2, 6 , 5, 7 and Dequeue the Queue = 4 and print = 4
Queue = 2, 6 , 5, 7
● Enqueue neighbouring nodes of 2,
Queue = 2, 6, 5, 7 and Dequeue the Queue = 2 and print = 2
Queue = 6, 5, 7
Graphs: BFS Traversal
1. Take a Start node
a. Put it in a Queue & Visited = NULL
2. Queue is NOT EMPTY
a. Enqueue the neighbouring nodes
b. Dequeue the node and print the node and mark as visited.
3. Repeat the steps until Queue is EMPTY
● Enqueue neighbouring nodes of 6,
Queue = 6, 5, 7 and Dequeue the Queue = 6 and print = 6
Queue = 5, 7
● Enqueue neighbouring nodes of 5,
Queue = 5, 7 and Dequeue the Queue = 5 and print = 5
Queue = 7
● Enqueue neighbouring nodes of 7,
Queue = 7 and Dequeue the Queue = 7 and print =7
Queue = NULL = STOP THE ALGO
#include <stdio.h> void bfs(int source) {
#include <stdlib.h> int v;
#include <stdbool.h> enqueue(source);
#define MAX_VERTICES 100 visited[source] = true;
int adjacency_matrix
[MAX_VERTICES][MAX_VERTICES]; while (!is_queue_empty()) {
bool visited[MAX_VERTICES]; int u = dequeue();
int queue[MAX_VERTICES], front = -1, printf("%d ", u);
rear = -1;
int vertices; for (v = 0; v < vertices; v++) {
void enqueue(int v) { if (adjacency_matrix[u][v] == 1 && !visited[v])
queue[++rear] = v; {
} enqueue(v);
int dequeue() { visited[v] = true;
return queue[++front]; }
} }
bool is_queue_empty() { }
return front == rear; }
}
int main() { OUTPUT:
int i,j;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);

printf("Enter the adjacency matrix:\n");


for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
scanf("%d",
&adjacency_matrix[i][j]);
}
}
printf("BFS: ");
bfs(0);
printf("\n");

return 0;
}
Depth-First Search Algorithm
Graphs: DFS
● Depth-first search (DFS) is a graph search algorithm
● It progresses by expanding the starting node of G and then going deeper and deeper until the goal
node is found, or until a node that has no children is encountered
● When a dead-end is reached, the algorithm backtracks, returning to the most recent node that has
not been completely explored.
● Its implementation is similar to that of the breadth-first search algorithm but here we use a stack
instead of a queue.
Graphs: DFS Traversal

https://www.cs.usfca.edu/~galles/visualization/DFS.html
Graphs: DFS Traversal
1. Start with a source vertex
a. Pop(v) and mark as visited
b. Visit all the unvisited neighbors of the source vertex.
2. Repeat 1 (a) and (b) for each unvisited neighbor
3. Repeat the process for all the vertices in the graph.

(1) Starting node = 0 (2) pop and print

0
Graphs: DFS Traversal
(1) Starting node = 0, push node to the stack S

(2) pop, print(v) and add the each unvisited neighbouring node of v

OUTPUT = 0
Edge (0,3) = new node, push (3)
0 Edge (0,4) = PENDING 3

(3) pop, print(v) and add the each unvisited neighbouring node of v
OUTPUT = 3
Edge(3,0)= node 0 is visited
3 Edge(3,5) = new node, push(5) 5
Edge (3,7) = PENDING

0 3
Graphs: DFS Traversal
(4) pop, print(v) and add the each unvisited neighbouring node of v

OUTPUT = 5
Edge (5,1) = new node, push (1)
5 5=> 2,3,6 = Pending 1

(5) pop, print(v) and add the each unvisited neighbouring node of v

OUTPUT = 1
Edge (1,2) = new node, push (2)
1 1=> 5,6 = Pending 2

(6) pop, print(v) and add the each unvisited neighbouring node of v
OUTPUT = 2
Edge(2,1)= node 1 is visited
2 Edge(2,4) = new node, push(4) 4
2=> 5 = Pending

0 3 5 1 2
Graphs: DFS Traversal
(7) pop, print(v) and add the each unvisited neighbouring node of v
OUTPUT = 4
Edge (4,0) = node 0 is visited
4 Edge (4,2) = node 2 is visited
No neighbouring nodes, so backtrack
Backtrack to 2

Edge(2,1)= node 1 is visited


Edge(2,4) = node 4 is visited
Edge (2,5) = node 5 is visited 2

Backtrack to 1
Edge (1,2) = node 2 is visited
Edge (1,5) = node 5 is visited
Edge (1,6) = new node, push (6) 6

0 3 5 1 2 4
Graphs: DFS Traversal
(8) pop, print(v) and add the each unvisited neighbouring node of v
OUTPUT = 6
Edge (6,1) = node1 is visited
6 Edge (6,5) = node 5 is visited 7
Edge (6,7) = new node, push(7)
(9) pop, print(v) and add the each unvisited neighbouring node of v

OUTPUT = 7
All nodes of the graph has been visited
7 STOP THE ALGORITHM

OUTPUT of DFS Traversal = 0 3 5 7 2 4 6 7

0 3 5 1 2 4 6 7
#include <stdio.h> int main() {
#include <stdbool.h> int i,j;
#define MAX_VERTICES 100 printf("Enter the number of vertices: ");
bool adjacency_matrix scanf("%d", &vertices);
[MAX_VERTICES][MAX_VERTICES];
bool visited[MAX_VERTICES]; printf("Enter the adjacency matrix:\n");
int vertices; for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
void dfs(int vertex) { scanf("%d", &adjacency_matrix[i][j]);
int i; }
visited[vertex] = true; }
printf("%d ", vertex);
printf("DFS: ");
for (i = 0; i < vertices; i++) { dfs(0);
if (adjacency_matrix[vertex][i] && printf("\n");
!visited[i]) {
dfs(i); return 0;
} } } }
Write a c program to implement BFS and DFS
UNIT VI Graphs and Hashing
Graphs:

● basic terminologies, representation of graphs, traversals (DFS, BFS) with complexity analysis,
● path finding (Dijkstra's SSSP, Floyd's APSP), and
● spanning tree (Prim's method) algorithms.

Hashing:

● Hash functions and hash tables,


● closed and open hashing,
● randomization methods (division method, mid-square method, folding),
● collision resolution techniques.
SHORTEST PATH ALGORITHMS
Path Finding: Introduction
Three different algorithms to calculate the shortest path between the vertices of a graph G.

● Minimum spanning tree


● Dijkstra’s algorithm
● Warshall’s algorithm

While the first two use an adjacency list to find the shortest path,
Warshall’s algorithm uses an adjacency matrix to do the same.
Minimum Spanning Tree: Introduction
● A spanning tree of a connected, undirected graph G is a sub-graph of G which is a tree that
connects all the vertices together.
● A graph G can have many different spanning trees
● We can assign weights to each edge
(Weights can represents how unfavourable the edge is)
● Weight to a spanning tree can be calculated by the sum of the weights of the edges in that spanning
tree

● A minimum spanning tree (MST) is defined as a spanning tree with weight less than or equal to
the weight of every other spanning tree.
● Analogy: A cable TV company laying cable in a new neighbourhood.
Minimum Spanning Tree: Properties
● Possible multiplicity: Multiple minimum spanning trees of the same weight.
● Uniqueness: When each edge in the graph is assigned a different weight, then there will be only
one unique minimum spanning tree.
● Minimum-cost subgraph: If the edges of a graph are assigned non-negative weights, then a
minimum spanning tree is in fact the minimum-cost subgraph or a tree that connects all vertices.
● Cycle property: If there exists a cycle C in the graph G that has a weight larger than that of other
edges of C, then this edge cannot belong to an MST.
● Usefulness: MST can be computed quickly and easily to provide optimal solutions.
● Simplicity: MST of a weighted graph is a spanning tree of the graph which comprises of n–1
edges of minimum total weight.
Note that for an unweighted graph, any spanning tree is a minimum spanning tree.
Minimum Spanning Tree: Unweighted Graphs
Minimum Spanning Tree: Weighted Graphs
Prim’s Algorithm

https://www.cs.usfca.edu/~galles/visualization/Prim.html
Prims: Introduction
● It is a greedy algorithm that is used to form a minimum spanning tree for a connected weighted
undirected graph

The algorithm maintains three sets of vertices:

● Tree vertices Vertices that are a part of the minimum spanning tree T.
● Fringe vertices Vertices that are currently not a part of T, but are adjacent to some tree vertex.
● Unseen vertices Vertices that are neither tree vertices nor fringe vertices fall under this category.
Prims: Create a MST
Prims: Create a MST
Kruskal’s Algorithm

https://www.cs.usfca.edu/~galles/visualization/Kruskal.html
Kruskal’s Algorithm
● It is used to find the minimum spanning tree for a connected weighted graph.
● It uses a priority queue Q in which edges that have minimum weight takes a priority over any
other edge in the graph
Kruskal’s: Create a MST

Step 1
F = {{A, D}, {B}, {C}, {E}, {F}}
MST = {A, D}
Q = {(E, F), (C, E), (E, D), (C, D), (D, F), (A, C), (A, B), (B, C)}

Step 2
F = {{A, D}, {B}, {C}, {E, F}}
MST = {(A, D), (E, F)}
Q = {(C, E), (E, D), (C, D), (D, F), (A, C), (A, B), (B, C)}

Step 3
F = {{A, D}, {B}, {C, E, F}}
MST = {(A, D), (C, E), (E, F)}
Q = {(E, D), (C, D), (D, F), (A, C), (A, B), (B, C)}
Kruskal’s: Create a MST
Step 4
F = {{A, C, D, E, F}, {B}}
MST = {(A, D), (C, E), (E, F), (E, D)}
Q = {(C, D), (D, F), (A, C), (A, B), (B, C)}
Step 5: Remove (C,D) and discard as it does not connect different trees
F = {{A, C, D, E, F}, {B}}
MST = {(A, D), (C, E), (E, F), (E, D)}
Q = {(D, F), (A, C), (A, B), (B, C)}
Step 6: Remove (D,F) and discard as it does not connect different trees
F = {{A, C, D, E, F}, {B}}
MST = {(A, D), (C, E), (E, F), (E, D)}
Q = {(A, C), (A, B), (B, C)}
Step 7:Remove (A,C) and discard as it does not connect different trees
F = {{A, C, D, E, F}, {B}}
MST = {(A, D), (C, E), (E, F), (E, D)}
Q = {(A, B), (B, C)}
Kruskal’s: Create a MST
Step 8
F = {A, B, C, D, E, F}
MST = {(A, D), (C, E), (E, F), (E, D), (A, B)}
Q = {(B, C)}

Step 9
F = {A, B, C, D, E, F}
MST = {(A, D), (C, E), (E, F), (E, D), (A, B)}
Q={}
Kruskal’s: Create a MST
Dijkstra’s Algorithm

https://www.cs.usfca.edu/~galles/visualization/Dijkstra.html
Dijkstra’s Algorithm
● It is given by a Dutch scientist Edsger Dijkstra in 1959, is used to find the shortest path tree
● It is used to find the length of an optimal path between two nodes in a graph
(The term optimal can mean anything, shortest, cheapest, or fastest)

● Objective: To find the shortest path (MCST) between source node and every other node.
● Applications: network routing protocols, the shortest route between one city and all other cities
Dijkstra’s Algorithm
Dijkstra’s Algorithm
Dijkstra’s Algorithm: Step 1
1) Starting Node: 0
Node Visited Cost
0 F INF
1 F INF
2 F INF
3 F INF
4 F INF
5 F INF
6 F INF
7 F INF
Dijkstra’s Algorithm: Step 2
a) Add the node N to the visited array and update its cost
=> Node 0 is added to the visited array. (Cost = 0)
b) Update labels of neighbouring nodes of node N
0(0) => 1(8) = 0 + 8 = 8
2(8) = 0 + 8 = 8
3(5) = 0 + 5 = 5 (Minimum Cost Node)
4(9) = 0 + 9 = 9
c) Choose the minimum Node Visited Cost
cost edge and add it to
the graph 0 T 0
1 F 8
=> Select 3
2 F 8
Continue the loop with 3 F T 5
the current node 4 F 9
until all the nodes are 5 F INF
VISITED 6 F INF
7 F INF
Dijkstra’s Algorithm: Step 3
a) Add the node N to the visited array and update its cost
=> Node 3 is added to the visited array. (Cost =5)
b) Update labels of neighbouring nodes of node N
3(5)=> 0(5) = Visited Node, skip
5(6) = 5 + 6 = 11
7(3) = 5 + 3 = 8
c) Choose the minimum cost edge and add it to the graph
=> Observe the visited array, Node Visited Cost
From top to bottom for 0 T 0
Minimum cost node, 1 F T 8
Hence, Select 1 (Cost=8) 2 F 8
3 T 5
4 F 9
Not all nodes are visited, 5 F 11
Continue Loop. 6 F INF
7 F 8
Dijkstra’s Algorithm: Step 4
a) Add the node N to the visited array and update its cost
=> Node 1 is added to the visited array. (Cost = 8)
b) Update labels of neighbouring nodes of node N
1(8)=> 0(8) = Visited Node, skip
2(8) = 8 + 8 = 16 (as 16>8, keep 8),drop this.
5(8)= 8 + 8 = 16 (as 16>11, keep 8), drop this
c) Choose the minimum cost edge and add it to the graph
=> Observe the visited array, Node Visited Cost
From top to bottom for 0 T 0
Minimum cost node, 1 T 8
Hence, Select 2 (Cost=8) 2 F T 8
3 T 5
4 F 9
Not all nodes are visited, 5 F 11
Continue Loop. 6 F INF
7 F 8
Dijkstra’s Algorithm: Step 5
a) Add the node N to the visited array and update its cost
=> Node 2 is added to the visited array. (Cost = 8)
b) Update labels of neighbouring nodes of node N
2(8)=>0(8) & 1(8) = Visited Node, skip
5(4) = 8 + 4 = 12 (as 12>11, keep 11), drop this.
6(4) = 8 + 4 = 12 (as 12 < INF, keep 12)
c) Choose the minimum cost edge and add it to the graph
=> Observe the visited array, Node Visited Cost
From top to bottom for 0 T 0
Minimum cost node, 1 T 8
Hence, Select 7 (Cost=8) 2 T 8
3 T 5
4 F 9
Not all nodes are visited, 5 F 11
Continue Loop. 6 F INF 12
7 F T 8
Dijkstra’s Algorithm: Step 6
a) Add the node N to the visited array and update its cost
=> Node 7 is added to the visited array. (Cost = 8)
b) Update labels of neighbouring nodes of node N
7(8)=>3(3) = Visited Node, skip
5(1) = 8 + 1 = 9 (as 9 < 11, keep 9)
6(6) = 8 + 6 = 14 (as 14>12, keep 12) drop this
c) Choose the minimum cost edge and add it to the graph
=> Observe the visited array, Node Visited Cost
From top to bottom for 0 T 0
Minimum cost node, 1 T 8
Hence, Select 4 (Cost=9) 2 T 8
3 T 5
4 F T 9
Not all nodes are visited, 5 F 11 9
Continue Loop. 6 F 12
7 T 8
Dijkstra’s Algorithm: Step 7
a) Add the node N to the visited array and update its cost
=> Node 4 is added to the visited array. (Cost = 9)
b) Update labels of neighbouring nodes of node N
4(9)=>0(9) = Visited Node, skip
6(2) = 9 + 2 = 11 (as 12>11, keep 11)
c) Choose the minimum cost edge and add it to the graph
=> Observe the visited array,
From top to bottom for Node Visited Cost
Minimum cost node, 0 T 0
Hence, Select 5 (Cost=9) 1 T 8
2 T 8
3 T 5
Not all nodes are visited,
4 T 9
Continue Loop. 5 F T 9
6 F 12 11
7 T 8
Dijkstra’s Algorithm: Step 8
a) Add the node N to the visited array and update its cost
=> Node 5 is added to the visited array. (Cost = 9)
b) Update labels of neighbouring nodes of node N
5(9)=>1(8), 2(4), 3(6) = Visited Node, skip
6(8) = 9 + 8 = 17 (as 17>11, keep 11), drop this
7(1) = Visited Node, skip
c) Choose the minimum cost edge and add it to the graph
=> Observe the visited array, Node Visited Cost
From top to bottom for 0 T 0
Minimum cost node, 1 T 8
Hence, Select 6 (Cost=11) 2 T 8
3 T 5
4 T 9
As all nodes are visited, 5 T 9
Stop the Algorithm. 6 F T 11
7 T 8
Dijkstra’s Algorithm: Final Output
As all nodes are visited, Stop the Algorithm.

Node Visited Cost


0 T 0
1 T 8
2 T 8
3 T 5
4 T 9
5 T 9
6 T 11
7 T 8
Dijkstra’s Algorithm: Paths of each node from the starting node
Difference between MST Algorithms and Dijkstra’s Algorithm
● MST algorithms are used to traverse a graph in the most efficient manner, but
Dijkstra’s algorithm calculates the distance from a given node to every other node in the graph.

● MST algorithm stores a minimum cost edge, but


Dijkstra’s algorithm stores the total cost from a source node to the current node

● MST algorithms stores at most one minimum cost edge, while


Dijkstra’s algorithm is used to store the summation of minimum cost edges
All Pairs Shortest Path
All Pairs Shortest Path
● MST algorithms are used to traverse a graph in the most efficient manner, but
Dijkstra’s algorithm calculates the distance from a given node to every other node in the graph.

● MST algorithm stores a minimum cost edge, but


Dijkstra’s algorithm stores the total cost from a source node to the current node

● MST algorithms stores at most one minimum cost edge, while


Dijkstra’s algorithm is used to store the summation of minimum cost edges

You might also like