0% found this document useful (0 votes)
14 views41 pages

DS Unit 5 2024

This document provides an overview of non-linear data structures, specifically graphs, detailing their components, types, and terminologies such as edges, vertices, paths, and cycles. It explains graph representation methods including adjacency matrices and lists, as well as traversal algorithms like Breadth First Search (BFS) and Depth First Search (DFS). Additionally, it discusses concepts such as connectedness, cut vertices, and directed acyclic graphs (DAGs).

Uploaded by

nctitacademic
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)
14 views41 pages

DS Unit 5 2024

This document provides an overview of non-linear data structures, specifically graphs, detailing their components, types, and terminologies such as edges, vertices, paths, and cycles. It explains graph representation methods including adjacency matrices and lists, as well as traversal algorithms like Breadth First Search (BFS) and Depth First Search (DFS). Additionally, it discusses concepts such as connectedness, cut vertices, and directed acyclic graphs (DAGs).

Uploaded by

nctitacademic
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
You are on page 1/ 41

Krishna/Unit 4/Data Structures 1

Unit 4
Non-Linear Data Structure – Graphs
Graphs:
It is a collection of two sets V & E, where V is a finite non empty set of vertices
& E is a finite non empty set of edge.
Any graph is denoted as G = {V, E}.
V(G)  vertices of graph G
E(G) Edges of graph G
Vertices are referred to as nodes & Edges are sometimes referred to as arcs.
Example:
A B

V(G1) = { A, B, C} & E(G1) = { (A,B) ( A,C) ( C,B)}

Basic Terminologies:
Undirected Edge:
Edges that does not indicates direction are called as undirected edge. We can travel either direction.

A B
Directed Edge:
Edges that have direction are called as directed edge. We can travel in one direction along the edge
i.e., form a to b & b to a.

A B

Path:
A sequence of vertices that connect a nodes in a graph is called graph.
V1

V2 V4
V3

V5 V6
Krishna/Unit 4/Data Structures 2

Adjacent Node:
Two nodes are adjacent if they are connected by an edge

1 7

1 is adjacent to 7, 7 is adjacent to 1.

1 7

1 is adjacent to 7.

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).

1 2

Loop or Self Loop:


It is an edge that connects the same vertex to itself.

V1

Parallel Edges:
Two undirected edges with same end vertices.

A B

Two directed edges with same origin & destination

A B
Krishna/Unit 4/Data Structures 3

Degree:
Number of edges associated with vertex.

1. In degree:
It is number of edges that come into the vertex.
In degree of A is 0
A B
In degree of B is 1
In degree of C is 2
C

2. Out degree:
It is the number of edges that comes out from the vertex.

A B
Out degree of A is 2
Out degree of B is 1
Out degree of C is 0
C

Connected:
An undirected graph is said to be connected if for every pair of distinct vertices Vi and Vj in V(G), there is a
path form Vi to Vj in G.

connected not connected

A directed graph is strongly connected if there is a path from every node to every other node.
Krishna/Unit 4/Data Structures 4

A directed graph is weakly connected if treating all edges being undirected, there is a path from every node to
every other node.

Disjoint:
A graph is said to be disjoint, if it is not connected.
A D

B C E

Cut Vertex: It is also known as articulation point. It is a vertex in connected graph whose deletion disconnects
it into two or more sub graphs

Directed Acyclic Graphs:


A directed acyclic graph or DAG is a directed graph with no directed cycles
Krishna/Unit 4/Data Structures 5

Types of Graph:
1. Directed Graph:
When one edges in a graph have direction, then the graph is called as directed graph
1 2

3
2. Undirected Graph:
When the edges in a graph have no direction, then the graph is called as undirected graph

1 2

3. Mixed Graph: 3
A mixed graph is one which contains both directed and undirected edge
1 2

4. Simple Graph:
A simple graph is one with no parallel edges and self loops. 3

5. Weighted Graph:
It is a graph which consists of weight along its edges. Here each edge carries a value.
10
A B

20 30
C

6. Complete Graph:
A graph in which every vertex is directly connected to every other vertex is called as completed graph.
For undirected. For Directed Graph
V1 V2 V1 V2
Number of edges = n (n -1) Number of edges = n (n -1)
4
V3 V4 V3 V4
Krishna/Unit 4/Data Structures 6

Representation of Graph:
Define Graph:
G = (V, E)
Graph is a collection of nodes or vertices (V) and edges(E) between them.
We can traverse these nodes using the edges. These edges might be weighted or non-weighted.
There can be two kinds of Graphs
1. Un-directed Graph – when you can traverse either direction between two nodes.
2. Directed Graph – when you can traverse only in the specified direction between two nodes.

Graph can be represented by two ways:


1. Adjacency Matrix Representation
2. Adjacency List Representation
1. Adjacency Matrix
 The Adjacency Matrix is used to which nodes are adjacent to one another.
 By definition, two nodes are said to be adjacent if there is an edge connecting them.
 Let G can be represented by an n * n matrix , such that
Aij = 1, if there is an edge Vi to Vj
0, if there is no edge
 Such a matrix is also called as Bit or Boolean Matrix
Example: 1
Adjacency Matrix for Directed Graph:

V1 V2 V1 V2 V3 V4

V1 0 1 1 0

V2 0 0 0 1

V3 0 1 0 0
V3 V4
V4 0 0 1 0
Krishna/Unit 4/Data Structures 7

Adjacency Matrix for Undirected Graph:

V1 V1 V2 V3 V4
V2
1 V1 0 1 1 0
V2 1 0 1 1
V3 1 1 0 1

V3 V4 V4 0 1 1 0

Adjacency Matrix for Weighted Graph


3 V1 V2 V3 V4
V1 V2
V1 0 3 9 ∞
9 1 7 ∞ 0 ∞ 7
V2
8
V3 ∞ 1 0 ∞

V3 V4 ∞ 1 8 0
V4

Example: 2

Advantage:
1. It is easier to implement and follow.
Disadvantage:
1. It requires huge effort for adding & removing a vertex
2. It consumes huge amount of memory for storing big graph.
Krishna/Unit 4/Data Structures 8

2. Adjacency List:
 An adjacency list is another way in which graphs can be represented in the computer’s memory.
 This structure consists of a list of all nodes in G. Furthermore, every node is in turn linked to its own list that
contains the names of all other nodes that are adjacent to it.
Example: 1

Example: 2

Advantage:
1. Adding a vertex is easy. It saves Spaces.
Disadvantage:
2. Queries like whether there is an edge from vertex u to vertex v are not efficient.
__________________________________________________________________________________________
Krishna/Unit 4/Data Structures 9

Graph Traversal:
 Most of graph problem involve traversal of a graph.
 Traversal of a graph means visiting each node and visiting exactly once.
Types of Graph Traversal:
1. Breadth First Search 2. Depth First Search
1. Breadth First Search (BFS):
 BFS is a graph traversal algorithm that begins at the root node and explores all the neighboring nodes.
 Data structure used is : Queue
Algorithm:
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: En-queue the starting node A and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: De-queue a node N. Process it and set its STATUS = 3 (processed state).
Step 5: En-queue all the neighbours of N that are in the ready state (whose STATUS = 1) and set their
STATUS = 2 (waiting state) [END OF LOOP]
Step 6: EXIT
Status State of the node Description
1 Ready The initial state of the node N
2 Waiting Node N is placed on the queue or stack and waiting to be processed
3 Processed Node N has been completely processed
Example: 1 Consider the graph G given in Fig.
The adjacency list of G is also given. Assume that G represents the daily flights between different cities and we
want to fly from city A to I with minimum stops. That is, find the minimum path P from A to I given that every
edge has a length of 1.

Solution
The minimum path P can be found by applying the breadth-first search algorithm that begins at city A and ends
when I is encountered. During the execution of the algorithm, we use two arrays:
Krishna/Unit 4/Data Structures 10

 QUEUE and ORIG.


While QUEUE is used to hold the nodes that have to be processed,
ORIG is used to keep track of the origin of each edge.
Initially, FRONT = REAR = –1.
The algorithm for this is as follows:

Step 1:
Add A to QUEUE and add NULL to ORIG.
FRONT =0 QUEUE =A
REAR =0 ORIG = \0

Step 2:
De-queue a node by setting FRONT = FRONT + 1 (remove the FRONT element of QUEUE) and
en-queue the neighbours of A.
Also, add A as the ORIG of its neighbours.
FRONT =1 QUEUE =ABCD
REAR =3 ORIG = \0 A A A

Step 3:
De-queue a node by setting FRONT = FRONT + 1 and
en-queue the neighbours of B.
Also, add B as the ORIG of its neighbours.
FRONT =2 QUEUE =ABCDE
REAR =4 ORIG = \0 A A A B

Step 4:
De-queue a node by setting FRONT = FRONT + 1 and
en-queue the neighbours of C.
Also, add C as the ORIG of its neighbours.
Note that C has two neighbours B and G.
Since B has already been added to the queue and it is not in the Ready state, we will not add B and only add G.
FRONT =3 QUEUE =ABCDEG
REAR =5 ORIG = \0 A A A B C
Krishna/Unit 4/Data Structures 11

Step 5:
De-queue a node by setting FRONT = FRONT + 1 and
en-queue the neighbours of D.
Also, add D as the ORIG of its neighbours.
Note that D has two neighbours C and G.
Since both of them have already been added to the queue and they are not in the Ready state, we will not add
them again.
FRONT =4 QUEUE =ABCDEG
REAR =5 ORIG = \0 A A A B C

Step 6:
De-queue a node by setting FRONT = FRONT + 1 and
en-queue the neighbours of E.
Also, add E as the ORIG of its neighbours.
Note that E has two neighbours C and F.
Since C has already been added to the queue and it is not in the Ready state, we will not add C and add only F.
FRONT =5 QUEUE =ABCDEGF
REAR =6 ORIG = \0 A A A B C E

Step 7:
De-queue a node by setting FRONT = FRONT + 1 and en-queue the neighbours of G. Also, add G as
the ORIG of its neighbours. Note that G has three neighbours F, H, and I.
FRONT =6 QUEUE =ABCDEGFHI
REAR =9 ORIG = \0 A A A B C E G G
Since F has already been added to the queue, we will only add H and I. As I is our final destination, we stop the
execution of this algorithm as soon as it is encountered and added to the QUEUE.
Now, backtrack from I using ORIG to find the minimum path P.
Thus, we have P as A -> C -> G -> I.
Krishna/Unit 4/Data Structures 12

Example: 2
r S t u

v w x v Take S as source

Step 1:
Enqueue S

Step 2: Dequeue s and enqueue its neighbors (w, r)


Enqueue w r
S
Dequeue S

Step 3: Dequeue w and enqueue its neighbors (t, x)


S
Enqueue r t x

Dequeue S w
w

Step 4: Dequeue r and enqueue its neighbors ( v )


Enqueue t x v r S

Dequeue s w r
w

Step 5: Dequeue t and enqueue its neighbors ( u )


Enqueue x v u r S t

Dequeue s w r t
w
Krishna/Unit 4/Data Structures 13

Step 6: Dequeue x and enqueue its neighbors ( y )


r S t
Enqueue v u y

Dequeue s w r t x w x

Step 7: Dequeue v and enqueue its neighbors ( no neighbors )


Enqueue u y
r S t

Dequeue s w r t x v
v w x

Step 8: Dequeue u and enqueue its neighbors ( t, y ) t is already visited, y is already in queue.
Enqueue y
r S t u

Dequeue s w r t x v u
v w x

Step 9: Dequeue y and enqueue its neighbors ( x, t ) neighbor of y ( x and t is already visited )
Enqueue
r S t u

Dequeue s w r t x v u y
v w x y
Krishna/Unit 4/Data Structures 14

2. Depth First Search (BFS):


 Depth First Search (DFS) algorithm traverses a graph in a depth-ward motion and uses a stack to remember
to get the next vertex to start a search, when a dead end occurs in any iteration.

Algorithm:
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbours of N that are in the ready state (whose STATUS = 1) and
set their STATUS = 2 (waiting state) [END OF LOOP]
Step 6: EXIT

Example: 1 Consider the graph G given in Fig. 13.23. The adjacency list of G is also given.
Suppose we want to print all the nodes that can be reached from the node H (including H itself). One alternative
is to use a depth-first search of G starting at node H. The procedure can be explained here.

Solution

Step 1:
Push H onto the stack. STACK: H

Step 2:
Pop and print the top element of the STACK, that is, H.
Push all the neighbours of H onto the stack that are in the ready state.
The STACK now becomes
PRINT: H STACK: E, I
Krishna/Unit 4/Data Structures 15

Step 3:
Pop and print the top element of the STACK, that is, I.
Push all the neighbours of I onto the stack that are in the ready state.
The STACK now becomes
PRINT: I STACK: E, F

Step 4:
Pop and print the top element of the STACK, that is, F.
Push all the neighbours of F onto the stack that are in the ready state.
(Note F has two neighbours, C and H. But only C will be added, as H is not in the ready state.)
The STACK now becomes
PRINT: F STACK: E, C

Step 5:
Pop and print the top element of the STACK, that is, C.
Push all the neighbours of C onto the stack that are in the ready state.
The STACK now becomes
PRINT: C STACK: E, B, G

Step 6:
Pop and print the top element of the STACK, that is, G.
Push all the neighbours of G onto the stack that are in the ready state.
Since there are no neighbours of G that are in the ready state, no push operation is performed.
The STACK now becomes
PRINT: G STACK: E, B

Step 7:
Pop and print the top element of the STACK, that is, B.
Push all the neighbours of B onto the stack that are in the ready state.
Since there are no neighbours of B that are in the ready state, no push operation is performed.
The STACK now becomes
PRINT: B STACK: E
Krishna/Unit 4/Data Structures 16

Step 8:
Pop and print the top element of the STACK, that is, E.
Push all the neighbours of E onto the stack that are in the ready state.
Since there are no neighbours of E that are in the ready state, no push operation is performed.
The STACK now becomes empty.
PRINT: E STACK:
Since the STACK is now empty, the depth-first search of G starting at node H is complete and the nodes which
were printed are:
H, I, F, C, G, B, E
These are the nodes which are reachable from the node H.

Features of Depth-First Search Algorithm


Space complexity The space complexity of a depth-first search is lower than that of a breadth first search.
Time complexity: Time complexity can be given as (O(|V| + |E|)).
BFS DFS
It requires more memory It requires less memory
BFS is slower than DFS DFS is faster than BFS
This process is done using queue is, FIFO This process is done using Stack is, LIFO
implementation implementation
BFS is a vertex based algorithm DFS is a edge based algorithm
BFS has insufficient memory consumption DFS has efficient memory consumption
Application
It is used to find shortest path It is used to find path between vertex and width in a
graph
It is used for single source and all pairs shortest paths It is used in finding spanning tree
It is used in spanning trees and connectivity testing It is used in cycle detection and connectivity testing
Krishna/Unit 4/Data Structures 17

Example: 2
r S t u

Take S as source vertex


v w x y

Step 1: push pop ‘s’ and push its neighbor

r
s
S w

Visited s

Step 2: pop ‘r’ and push its neighbor ( v )

v r s
w

Visited s r

Step 3: pop ‘v’ and push its neighbor ( w )

r s

w
v
Visited s r v

Step 4: pop ‘w’ and push its neighbor ( s, t, x ) and s is already visited

r s

t
v w
Krishna/Unit 4/Data Structures 18

Visited s r v w

Step 5: pop ‘t’ and push its neighbor ( w, x, t ) and w is already visited

r s t

u
x v w

Visited s r v w t

Step 6: pop ‘u’ and push its neighbor ( t, y ) and t is already visited

r s t u
y
x
v w
Visited s r v w t u

Step 7: pop ‘y’ and push its neighbor ( u, x ) and u is already visited

r s t u

x
v w y

Visited s r v w t u y

Step 8: pop ‘x’ and push its neighbor (Its neighbor are already visited )

r s t u
Visited s r v w t u y x

v w x y

__________________________________________________________________________________________
Krishna/Unit 4/Data Structures 19

Topological Sort:
 A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that
for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.
 A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed
acyclic graph (DAG).
Algorithm
Step 1: Find the in-degree for each and every vertex.
Step 2: Find the vertices whose in-degree is zero (‘0’).
Step 3: Delete the vertex V and decrement the indegree’s of all its adjacent vertices.
Step 4: Put the vertex, deleted from the graph, in the desired queue.
Step 5: Repeat from step 3 until the queue becomes empty.
Application:
1. Job Scheduling
2. Application Scheduling V1 V2
3. Tasks Scheduling 1
Example: 1
V3 V4 V5

V6 V7
Step 1: Find the indegree of all the vertices
Indegree [v1] = 0
Indegree [v1] = 1
V2
Indegree [v2] = 2
Indegree [v3] = 3
Indegree [v4] = 1
V3 V4 V5
Indegree [v5] = 3
Indegree [v6] = 2

Delete V1 from the graph and put it in the queue. V6 V7


Delete: V1
Krishna/Unit 4/Data Structures 20

Step 2: After deletion of V1


V2
Indegree [v2] = 0
Indegree [v3] = 1
Indegree [v4] = 2
V3 V4 V5
Indegree [v5] = 1
Indegree [v6] = 3
Indegree [v7] = 2
Delete V2 from the graph and put it in the queue
V6 V7

Delete : V 1 V2

Step 3: After deletion of V1 and V2


Indegree [v3] = 1
V3 V4 V5
Indegree [v4] = 1
Indegree [v5] = 0
Indegree [v6] = 3
V6 V7
Indegree [v6] = 2
Delete V5 from the graph and put it in the queue
Delete : V 1 V2 V5

Step 4: After deletion of V1 ,V2 and V5


Indegree [v3] = 1 V3 V4
Indegree [v4] = 0
Indegree [v6] = 3
Indegree [v7] = 1
V6 V7
Delete V4 from the graph and put it in the queue
Delete : V1 V2 V5 V4

Step 5: After deletion of V1 ,V2 ,V5 and V4


Indegree [v3] = 0 V3
Indegree [v6] = 1
Indegree [v7] = 0
V6 V7
Krishna/Unit 4/Data Structures 21

Delete V3 from the graph and put it in the queue


Delete : V 1 V2 V5 V4 V 3

Step 6: After deletion of V1 ,V2 ,V5 ,V4 and V3


Indegree [v6] = 1
Indegree [v7] = 0
Delete V7 from the graph and put it in the queue
Delete : V1 V2 V5 V4 V3 V7 V6 V7

Step 8: After deletion of V1 ,V2 ,V5 ,V4 , V3 and V7


Indegree [v6] = 0
Delete V6 from the graph and put it in the queue V6
Delete : V1 V2 V5 V4 V3 V7 V6

So the topological order is


V1 V2 V5 V4 V3 V7 V6

Example: 2 consider a directed acyclic graph G given in Fig. We use the algorithm given above to find a
topological sort T of G. The steps are given as below:
Solution:

Step 1:
Find the in-degree INDEG(N) of every node in the graph
INDEG(A) = 0
INDEG(B) = 1
INDEG(C) = 1
INDEG(D) = 2
INDEG(E) = 3
INDEG(F) = 1
INDEG(G) = 0
Krishna/Unit 4/Data Structures 22

Step 2:
En-queue all the nodes with a zero in-degree
FRONT = 1 REAR = 2 QUEUE = A, G
Step 3:
Remove the front element A from the queue by setting FRONT = FRONT + 1, so
FRONT = 2 REAR = 2 QUEUE = A, G

Step 4:
Set INDEG(B) = INDEG(B) – 1, since B is the neighbour of A.

Note that INDEG(B) is 0, so add it on the queue. The queue now becomes
FRONT = 2 REAR = 3 QUEUE = A, G, B
Delete the edge from A to B. The graph now becomes as shown in the figure below

Step 5:
Remove the front element B from the queue by setting FRONT = FRONT + 1, so
FRONT = 2 REAR = 3 QUEUE = A, G, B

Step 6:
Set INDEG(D) = INDEG(D) – 1, since D is the neighbour of G.
Now,INDEG(C) = 1 INDEG(D) = 1 INDEG(E) = 3 INDEG(F) = 1
Delete the edge from G to D. The graph now becomes as shown in the figure below

Step 7:
Remove the front element B from the queue by setting FRONT = FRONT + 1, so
FRONT = 4 REAR = 3 QUEUE = A, G, B
Krishna/Unit 4/Data Structures 23

Step 8:
Set INDEG(C) = INDEG(C) – 1,
INDEG(D) = INDEG(D) – 1,
INDEG(E) = INDEG(E) – 1,
since C, D, and E are the neighbours of B.
Now, INDEG(C) = 0, INDEG(D) = 1 and INDEG(E) = 2

Step 9:
Since the in-degree of node c and D is zero, add C and D at the rear of the queue.
The queue can be given as below:
FRONT = 4 REAR = 5 QUEUE = A, G, B, C, D
The graph now becomes as shown in the figure below

Step 10:
Remove the front element C from the queue by setting FRONT = FRONT + 1, so
FRONT = 5 REAR = 5 QUEUE = A, G, B, C, D

Step 11:
Set INDEG(E) = INDEG(E) – 1, since E is the neighbour of C. Now, INDEG(E) = 1

Step 12:
Remove the front element D from the queue by setting FRONT = FRONT + 1, so
FRONT = 6 REAR = 5 QUEUE = A, B, G, C, D

Step 13:
Set INDEG(E) = INDEG(E) – 1, since E is the neighbour of D. Now, INDEG(E) = 0, so add E to the queue.
The queue now becomes.
FRONT = 6 REAR = 6 QUEUE = A, G, B, C, D, E
Krishna/Unit 4/Data Structures 24

Step 14:
Delete the edge between D an E. The graph now becomes as shown in the figure below

Step 15:
Remove the front element D from the queue by setting FRONT = FRONT + 1, so
FRONT = 7 REAR = 6 QUEUE = A, G, B, C, D, E

Step 16:
Set INDEG(F) = INDEG(F) – 1, since F is the neighbour of E. Now INDEG(F) = 0, so add F to the queue. The
queue now becomes,
FRONT = 7 REAR = 7 QUEUE = A, G, B, C, D, E, F

Step 17:
Delete the edge between E and F. The graph now becomes as shown in the figure below

There are no more edges in the graph and all the nodes have been added to the queue, so the topological sort T
of G can be given as: A, G, B, C, D, E, F. When we arrange these nodes in a sequence, we find that if there is an
edge from u to v, then u appears before v.

__________________________________________________________________________________________________________________________
Krishna/Unit 4/Data Structures 25

Applications of Graph:
 Telephone cabling graph theory is effective used
 Electronic Circuits
o Printed Circuit Board
o Integrated Circuit
 Transportation networks
o Highway networks
o Water Supply networks
o Flight network
 Computer networks
o Local Area Network
o Internet
o Web
 Databases
o Entity Relationship Diagram
Krishna/Unit 4/Data Structures 26

Shortest Path Algorithm:


In an edge-weighted graph, the weight of an edge measures the cost of traveling that edge.
For example, in a graph representing a network of airports, the weights could represent: distance, cost
or time.
Dijkstra’s Algorithm: (or) single-source shortest path problem
 Dijkstra's algorithm solves the single-source shortest path problem for a non-negative weights graph.
 It finds the shortest path from an initial vertex, say s, to all the other vertices.
 For example, if the vertices of the graph represent cities and edge path costs represent driving
distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find
the shortest route between one city (a) and destination city (b).
Algorithm:
Step 1: Mark all nodes unvisited and store them.
Step 2: Set the distance to zero for our initial node and to infinity for other nodes.
Step 3: Select the unvisited node with the smallest distance, it's current node now.
Step 4: Find unvisited neighbors for the current node and calculate their distances through the current
node.
Compare the newly calculated distance to the assigned and save the smaller one.
For example, if the node A has a distance of 6, and the A-B edge has length 2, then the distance to
B through A will be 6 + 2 = 8.
If B was previously marked with a distance greater than 8 then change it to 8.
Step 5: Mark the current node as visited and remove it from the unvisited set.
Step 6: Stop, if the destination node has been visited (when planning a route between two specific nodes)
or if the smallest distance among the unvisited nodes is infinity. If not, repeat steps 3-6.

Example 1:
Krishna/Unit 4/Data Structures 27

Step 1:
U = {1} V - U = {2, 3, 4, 5, 6,7}
Closest Lowcost
V–U U
V2 V1 2
V3 0 ∞
V4 V1 1
V5 0 ∞
V6 0 ∞
V7 0 ∞
Select vertex V4 to include in U
Iteration 1, U= [ 1]
0
V1

V4 1
Step 2:

U = {1, 4} V - U = {2, 3, 5, 6,7}


Closest Lowcost
V–U U
V2 V1 2
V3 V1, V4 3
V5 V1, V4 3
V6 V1, V4 9
V7 V1, V4 5

Select vertex V2 to include in U


0 V1 V1
2
Iteration 2, U= [ 1, 4]
1 1

V4
1
Krishna/Unit 4/Data Structures 28

Step 3:

U = {1, 4, 2} V - U = {3, 5, 6,7}


Closest Lowcost
V–U U
V3 V1, V4 3
V5 V1, V4 3
V6 V1, V4 9
V7 V1, V4 5

Select vertex V3 to include in U


Iteration 3, U= [ 1, 4, 2] 0 V1 V2 2

1 1

V3 V4
3 1
Step 4:

U = {1, 4, 2, 3} V - U = {5, 6,7}


Closest Lowcost
V–U U
V5 V1, V4 3
V6 V1, V4 9
V7 V1, V4 5

Select vertex V5 to include in U


V1 V2
Iteration 4, U= [ 1, 4, 2, 3] 0 2
1 1

3 V3 V4 1 V5 3
Step 5:

U = {1, 4, 2, 3, 5} V - U = { 6, 7}
Closest Lowcost
V–U U
V6 V1, V4 9
V7 V1, V4 5
Krishna/Unit 4/Data Structures 29

Select vertex V7 to include in U


V1 V2
Iteration 5, U= [ 1, 4, 2, 3, 5] 0 2
1 1

V3 V4 V5
3 1 3

5
V7
Step 6:

U = {1, 4, 2, 3, 5, 7} V-U={6}
Closest Lowcost
V–U U
V6 V1, V4 9

Select vertex V6 to include in U


Iteration 6, U= [ 1, 4, 2, 3, 5, 7]
0 2
V1 V2

1 1

3 V4
V3 V5
1 3

2V6 V7
7 5
After adding vertex 6.
Iteration 6, U= [ 1, 4, 2, 3, 5, 7]
The Shortest distance from the source vertex V1 to all other vertex is listed below:
V1  V2 is 2
V1  V3 is 3
V1  V4 is 1
V1  V5 is 3
V1  V6 is 6
V1  V7 is 5
Krishna/Unit 4/Data Structures 30

Minimum Spanning Tree:

Spanning Tree:
Spanning tree is a connected graph is its connected acyclic sub graph (i.e. tree) that contains all the vertices of
the graph

Minimum Spanning Tree:


A minimum spanning tree of a weighted connected graph is its graph is its spanning tree of the smallest weight,
where the weight of a tree is defined as the sum of the weight on all its edges.

Example:
The number of spanning tree grows exponentially with the graph size.
Second generating all spanning tree for a given graph is not easy; it is more difficult than finding a minimum
spanning tree.

1 1
A B A B

2 2
5

C D C D

3 3

1 1
A B A B
2
5 5
3
C D C D
5

Application of Spanning Tree:


1. Spanning trees are very important in designing efficient routing algorithms.
2. Spanning trees have wide application in many areas such as network design.
3. Analysis of electrical circuit.
4. Shortest route problems.
Krishna/Unit 4/Data Structures 31

Shortest Path Algorithm:


Two algorithms are used in finding minimum cost spanning trees
1. Kruskal’s Algorithm
2. Prims’ Algorithm
Kruskal’s Algorithm
 Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the
subset of the edges of that graph which form a tree that includes every vertex
 has the minimum sum of weights among all the trees that can be formed from the graph
Algorithm Steps:
Step 1: Sort all the edges from low weight to high
Step 2: Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle,
then reject this edge.
Step 3: Keep adding edges until we reach all vertices.
Example: 1

Step: 1
After Sorting
Weight Source Destination
V1 V2
1 V1 V4
1
1 V6 V7
2 V1 V2 V3 V4 V5

2 V3 V4
3 V2 V4
V6 V7
4 V1 V3
4 V4 V7
5 V3 V6
Krishna/Unit 4/Data Structures 32

Step: 2 V1 V2

1
1
V3 V4 V5

V6 V7

Step: 3

V1 V2

1
1

V3 V4 V5

1
V6 V7

Step: 4
V1 2 V2

1
1
V3 V4 V5

V6 V7
1
Step: 5 2
V1 V2

1
1
2
V3 V4 V5

1
V6 V7
Krishna/Unit 4/Data Structures 33

Step: 6 2
V1 V2

1 1

V3 2 V4 V5

4
V6 V7
1

Step: 7 2
V1 V2

1
1
V3 2 V4 V5
4 6

V6 1 V7

Weight Source Destination Action


1 V1 V4 Accepted
1 V6 V7 Accepted
2 V1 V2 Accepted
2 V3 V4 Accepted
3 V2 V4 Rejected
4 V1 V3 Rejected
4 V4 V7 Accepted
5 V3 V6 Rejected
6 V5 V7 Accepted

Sum the weights of tree is 16


Krishna/Unit 4/Data Structures 34

Example: 2

After Sorting
Weight Source Destination
1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5

Step: 1 Step: 2 Step: 3

Step: 4 Step: 5
Krishna/Unit 4/Data Structures 35

Step: 6 Step: 7

Step: 8
Weight Source Destination Action
1 7 6 Accepted
2 8 2 Accepted
2 6 5 Accepted
4 0 1 Accepted
4 2 5 Accepted
6 8 6 Rejected
7 2 3 Accepted
7 7 8 Rejected
8 0 7 Accepted
8 1 2 Rejected
9 3 4 Accepted
Sum of the weights of tree is 28 10 5 4 Rejected
11 1 7 Rejected
14 3 5 Rejected

-------------------------------------------------------------------------------------------------------------------------------------
Krishna/Unit 4/Data Structures 36

Prim’s Algorithm:
 Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the subset of
the edges of that graph which
 form a tree that includes every vertex
 has the minimum sum of weights among all the trees that can be formed from the graph
Algorithm Steps:
Step 1: Initialize the minimum spanning tree with a vertex chosen at random.
Step 2: Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree
Step 3: Keep repeating step 2 until we get a minimum spanning tree

Example: 1

Step 1: Select vertex V4 to include in U

U = {1} V - U = {2, 3, 4, 5, 6,7}


Closest Lowcost
V–U U
V2 V1 2
V3 V1 4
V4 V1 1
V5 - ∞
V6 - ∞
V7 - ∞

Iteration 1, U= [ 1]

V1

1
1
V4
Krishna/Unit 4/Data Structures 37

Step 2:
U = {1,4} V - U = {2, 3, 5, 6, 7}
Closest Lowcost
V–U U
V2 V1 2
V3 V4 2
V5 V4 7
V6 V4 8
V7 V4 4

Now select vertex 2


Iteration 2, U= [ 1, 4] V1 2 V2

1
1
V4

Step 3:
U = {1, 2, 4} V - U = {3, 5, 6, 7}
Closest Lowcost
V–U U
V3 V4 2
V5 V4 7
V6 V3 5
V7 V4 4

Now select vertex 3


Iteration 3, U= [ 1, 2, 4 ]
2
V1 V2

1
1
V3 2 V4
Krishna/Unit 4/Data Structures 38

Step 4:
U = {1, 2, 3, 4} V - U = {5, 6, 7}
Closest Lowcost
V–U U
V5 V7 6
V6 V7 1
V7 V4 4
Now select vertex 7, and so on
2
V1 V2
Iteration 4, U= [ 1, 2, 3, 4 ]
1
1
V3 V4

2 4

V7

Step 5:
U = {1, 2, 3, 4,7} V - U = {5, 6}
Closest Lowcost
V–U U
V5 V7 6
V6 V7 1
Now select vertex 6.
Iteration 5, U= [ 1, 2, 3, 4, 7 ]
2
V1 V2

1 1

V3 V4
2 4
1
V6 V7
Krishna/Unit 4/Data Structures 39

Step 6:
U = {1, 2, 3, 4,7, 6} V - U = {5}

Closest Lowcost
V–U U
V5 V7 6
Now select vertex 5.
Iteration 5, U= [ 1, 2, 3, 4, 6, 7 ]
2
V1 V2
1
1

V3 2 V4 V5

4 6
1
V6 V7

After adding vertex 5, this is the minimal spanning tree and its total weight is (1+1+2+2+4+6) = 16
-------------------------------------------------------------------------------------------------------------------------------------
Krishna/Unit 4/Data Structures 40

Warshall’s Algorithm:
 Warshall’s algorithm is a dynamic programming algorithm which is used to find the shortest path in an
unweighted graph.
 Here, the graph is unweighted, so it is possible to find the path length between every node in a graph.
 Warshall’s algorithm is based on the concept of transitive closure which is defined as follows.

Diagraph:
The graph in which all the edges are directed then it is called diagraph or directed.

a b

c d

Adjacency Matrix
The Adjacency Matrix A for a graph G=(V,E) with vertices is an n * n matrix , such that

1, if ther e is an edge Vi to Vj
Aij = 0, if there is no edge

Adjacency Matrix for Directed Graph:

a b c d
a b
a 0 1 1 0

b 0 0 0 1

c 0 1 0 0
c d d 0 0 1 0

Transitive Closure of a Graph – Definition


 Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the
given graph. Here, reachable means that there is a path from vertex i to j.
 The reach-ability matrix is called transitive closure of a graph.
Krishna/Unit 4/Data Structures 41

a b a b c d

a 1 1 1 1

b 1 1 1 1

c d
c 0 0 0 0

d 1 1 1 1

Example 1: Consider a directed graph as shown below.

a b

c d

A(0) a b c d A(1) a b c d

a 0 1 0 0 a 0 1 0 0
b 0 0 0 1 b 0 0 0 1
c 0 0 0 0 c 0 0 0 0

d 1 0 1 0 d 1 1 1 0

A(2) a b c d A(3) a b c d A(4) a b c d

a 0 1 0 1 a 0 1 0 1 a 1 1 1 1

b 0 0 0 1 b 0 0 0 1 b 1 1 1 1
c 0 0 0 0 c 0 0 0 0 c 0 0 0 0

d 1 1 1 1 d 1 1 1 1 d 1 1 1 1

You might also like