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

DSA_Unit3_Graph

Uploaded by

bsjadhav.foe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

DSA_Unit3_Graph

Uploaded by

bsjadhav.foe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

DSA UNIT 3 GRAPH

Graph:
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of
vertices and E(G) represents the set of edges which are used to connect these vertices.
A graph can be defined as group of vertices and edges that are used to connect these
vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any
complex relationship among them instead of having parent child relationship.
Graph algorithms are methods used to manipulate and analyze graphs, solving
various problems like finding the shortest path or detecting cycles.
Graph is a non linear data structure; A map is a well-known example of a graph. In a
map various connections are made between the cities. The cities are connected via
roads, railway lines and aerial network. We can assume that the graph is the
interconnection of cities by roads. Euler used graph theory to solve Seven Bridges of
Königsberg problem. Is there a possible way to traverse every bridge exactly once –
Euler Tou
A graph is a non-linear kind of data structure made up of nodes or vertices and edges.
The edges connect any two nodes in the graph, and the nodes are also known as
vertices.
Example 1:
This graph has a set of vertices V= { 1,2,3,4,5} and a set of edges E= {
(1,2),(1,3),(2,3),(2,4),(2,5),(3,5),(4,50 }.

Example 2:

In the graph,

V = {0, 1, 2, 3}

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 1


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

E = {(0,1), (0,2), (0,3), (1,2)}

G = {V, E}

Graph Terminology

1. Node :
Every individual element in a graph is known as Vertex. Vertex is also known as
Node.
OR
An individual data element of a graph is called as Vertex. Vertex is also known as
node. In above example graph, A, B, C, D & E are known as vertices

2.Edge :
An edge is a connecting link between two vertices. Edge is also known as Arc. An
edge is represented as (starting Vertex, ending Vertex).
In above graph, the link between vertices A and B is represented as (A,B).
Edges are three types:
a) Undirected Edge - An undirected edge is a bidirectional edge. If there is an
undirected edge between vertices A and B then edge (A , B) is equal to edge (B
, A).

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 2


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

b. Directed Edge - A directed edge is a unidirectional edge. If there is a directed edge


between vertices A and B then edge (A , B) is not equal to edge (B , A)

c. Weighted Edge - A weighted edge is an edge with cost on it.

3. Types of Graphs
a. Undirected Graph
 A graph with only undirected edges is said to be undirected graph.
 An undirected graph is a graph where the edges do not have a specific direction
and it is bidirectional in nature it does not have a parent-child relation concept
as there is no particular direction.
Example1:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 3


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

 An undirected graph is shown in the above figure since its edges are not
attached with any of the directions. If an edge exists between vertex A and B
then the vertices can be traversed from B to A as well as A to B.
Example 2:

b. Directed Graph
 A graph with only directed edges is said to be directed graph.
 In a directed graph, edges form an ordered pair. Edges represent a specific path
from some vertex A to another vertex B. Node A is called initial node while
node B is called terminal node.
 A directed graph is shown in the following figure.

Differences between Undirected Graph & Directed Graph:

S.N Undirected Graph Directed Graph

It is simple to understand and It provides a clear representation of


1 manipulate. relationships with direction.

It offers efficient traversal in the specified


It has the symmetry of a relationship.
2 direction.

It requires less memory hence memory It is suitable for modeling processes or


3 efficient. workflows.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 4


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

S.N Undirected Graph Directed Graph

It provides limited modeling capability It is complex as compared to undirected


4 for directed relationships graphs.

Inefficient traversal without additional It has a lack of symmetry, unlike an


5 checks. undirected graph.

It is difficult to represent specific It may require increased memory usage


6 scenarios. compared to undirected graphs.

c. Complete Graph
 A graph in which any V node is adjacent to all other nodes present in the graph
is known as a complete graph. An undirected graph contains the edges that are
equal to edges = n(n-1)/2 where n is the number of vertices present in the
graph. The following figure shows a complete graph.

d . Regular Graph
 Regular graph is the graph in which nodes are adjacent to each other, i.e., each
node is accessible from any other node.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 5


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

e. Cycle Graph
 A graph having cycle is called cycle graph. In this case the first and last nodes
are the same. A closed simple path is a cycle

f. Acyclic Graph
 A graph without cycle is called acyclic graphs

g. Weighted Graph
 A graph is said to be weighted if there are some non negative value assigned to
each edges of the graph. The value is equal to the length between two vertices.
Weighted graph is also called a network.
 In a weighted graph, each edge is assigned with some data such as length or
weight. The weight of an edge e can be given as w(e) which must be a positive
(+) value indicating the cost of traversing the edge.

4. Outgoing Edge
 A directed edge is said to be outgoing edge on its orign vertex.

5. Incoming Edge
 A directed edge is said to be incoming edge on its destination vertex.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 6


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

6. Degree
 Total number of edges connected to a vertex is said to be degree of that vertex.
 A degree of a node is the number of edges that are connected with that node. A
node with degree 0 is called as isolated node.
i. In-degree
 Total number of incoming edges connected to a vertex is said to be indegree of
that vertex.

 Consider the above directed graph for calculation of indegree of a node or


vertex.
 For calculating the indegree, we calculate the number of arrows pointing
towards the node. For e.g. for vertex V4 there are two arrows pointing toward
the node with edges as e3 and e4. therefore Indegree(V4) =2
Similarly,
Indegree(V5) =1 as there is only one arrow with edge e5.
Indegree(V1) =1 as there is only one arrow with edge e6.
Indegree(V2) =2 as there are two arrows with edges e1 and e7.
Indegree(V3) =1 as there is only one arrow with edge e2.
This is how we calculate the indegree of a node in a directed graph.

ii. Out-degree
 Total number of outgoing edges connected to a vertex is said to be outdegree of
that vertex
 The outdegree of a directed graph vertex, which reflects the total number of
edges emanating from that node, is always positive and never negative.
 If a directed graph’s vertex does not have any edges leading to other vertices,
then its outdegree will be 0.
 The total number of edges in a graph is equal to the sum of all outdegrees
because in a directed graph, there is precisely one vertex at each end of each
edge.
 Vertices with an outdegree of zero are known as sink vertices.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 7


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

How to calculate Outdegree of a Node?

Consider the above directed graph. To determine a vertex’s outdegree in a directed


graph, one must count the number of directed edges that leave from that vertex.
How to determine a vertex’s outdegree in a directed graph is as follows:
 Choose to pick the vertices whose outdegrees you wish to know about.
 Check how many outgoing directed edges there are from that vertex by going
along the edges of the graph.
 Keep track of how many directed edges in total come from that node.
 The vertex’s outdegree is equal to this number.
In the above graph, there is only one outgoing edge from the vertex (V1) i.e. edge e1.
Hence the outdegree of the vertex (V1) is 1. Similarly,
 Outdegree (V2) = 2 as there are two outgoing edges e2 and e4.
 Outdegree (V3) = 1 as there is only one outgoing edge e3.
 Outdegree (V4) = 1 as there is only one outgoing edge e5.
 Outdegree (V5) = 2 as there are two outgoing edges e6 and e7.

Adjacent nodes :
A node ‘v’ is said to be adjacent node of node ‘u’ if and only if there exists an edge
between ‘u’ and ‘v’.
OR
When there is an edge from one node to another then these nodes are called adjacent
nodes.

Storage Representation
A graph is a data structure that consist a sets of vertices (called nodes) and edges.
There are two ways to store Graphs into the computer's memory:
 Sequential representation (or, Adjacency matrix representation)
 Linked list representation (or, Adjacency list representation)

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 8


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

1. Sequential representation (or, Adjacency matrix representation)


1. In sequential representation, there is a use of an adjacency matrix to represent
the mapping between vertices and edges of the graph. We can use an
adjacency matrix to represent the undirected graph, directed graph,
weighted directed graph, and weighted undirected graph.
2. If adj[i][j] = w, it means that there is an edge exists from vertex i to vertex j
with weight w.
3. An entry Aij in the adjacency matrix representation of an undirected graph G
will be 1 if an edge exists between Vi and Vj. If an Undirected Graph G
consists of n vertices, then the adjacency matrix for that graph is n x n, and the
matrix A = [aij] can be defined as -
aij = 1 {if there is a path exists from Vi to Vj}
aij = 0 {Otherwise}
4. It means that, in an adjacency matrix, 0 represents that there is no association
exists between the nodes, whereas 1 represents the existence of a path between
two edges.
5. If there is no self-loop present in the graph, it means that the diagonal entries of
the adjacency matrix will be 0.
6. Now, let's see the adjacency matrix representation of an undirected graph.
7. An adjacency matrix is a 2D array of V x V vertices. Each row and column
represent a vertex.
8. If the value of any element a[i][j] is 1, it represents that there is an edge
connecting vertex i and vertex j.
Example-1

9. In the above figure, an image shows the mapping among the vertices (A, B, C,
D, E), and this mapping is represented by using the adjacency matrix.
10. There exist different adjacency matrices for the directed and undirected graph.
In a directed graph, an entry Aij will be 1 only when there is an edge directed
from Vi to Vj.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 9


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example-2:

Example-3:
The adjacency matrix for the graph we created above is

Since it is an undirected graph, for edge (0,2), we also need to mark edge (2,0); making the
adjacency matrix symmetric about the diagonal.
Edge lookup(checking if an edge exists between vertex A and vertex B) is extremely fast in
adjacency matrix representation but we have to reserve space for every possible link between
all vertices(V x V), so it requires more space
Example-4:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 10


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example-5:
 Adjacency matrix representation makes use of a matrix (table) where the first row
and first column of the matrix denote the nodes (vertices) of the graph. The rest of
the cells contains either 0 or 1 (can contain an associated weight w if it is a
weighted graph).
 Each row X column intersection points to a cell and the value of that cell will help us
in determining that whether the vertex denoted by the row and the vertex denoted by
the column are connected or not. If the value of the cell for v1 X v2 is equal to 1, then
we can conclude that these two vertices v1 and v2 are connected by an edge, else they
aren't connected at all.
Consider the given graph below:

The graph shown above is an undirected one and the adjacency matrix for the same looks
as:

Adjacency matrix for a directed graph


In a directed graph, edges represent a specific path from one vertex to another vertex.
Suppose a path exists from vertex A to another vertex B; it means that node A is the initial
node, while node B is the terminal node.
Consider the below-directed graph and try to construct the adjacency matrix of it.
Example 1:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 11


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

In the above graph, we can see there is no self-loop, so the diagonal entries of the adjacent
matrix are 0.

Example 2:

Adjacency matrix for a weighted directed graph


It is similar to an adjacency matrix representation of a directed graph except that instead of
using the '1' for the existence of a path, here we have to use the weight associated with the
edge. The weights on the graph edges will be represented as the entries of the adjacency
matrix. We can understand it with the help of an example. Consider the below graph and its
adjacency matrix representation. In the representation, we can see that the weight associated
with the edges is represented as the entries in the adjacency matrix.

In the above image, we can see that the adjacency matrix representation of the weighted
directed graph is different from other representations. It is because, in this representation, the
non-zero values are replaced by the actual weight assigned to the edges.
Adjacency matrix is easier to implement and follow. An adjacency matrix can be used when
the graph is dense and a number of edges are large.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 12


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

2. Linked list representation (or, Adjacency list representation)


 An adjacency list is used in the linked representation to store the Graph in the
computer's memory. It is efficient in terms of storage as we only have to store the
values for edges.
 An adjacency list represents a graph as an array of linked lists. The index of the array
represents a vertex and each element in its linked list represents the other vertices that
form an edge with the vertex.
 An array of Lists is used to store edges between two vertices. The size of array is
equal to the number of vertices (i.e, n). Each index in this array represents a specific
vertex in the graph. The entry at the index i of the array contains a linked list
containing the vertices that are adjacent to vertex i.
 Let’s assume there are n vertices in the graph So, create an array of list of
size n as adjList[n].
adjList[0] will have all the nodes which are connected (neighbour) to vertex 0.
adjList[1] will have all the nodes which are connected (neighbour) to
vertex 1 and so on.

Representation of Undirected Graph to Adjacency list:


Example 1:

The below undirected graph has 3 vertices. So, an array of list will be created of size 3,
where each indices represent the vertices. Now, vertex 0 has two neighbours (i.e, 1 and 2).
So, insert vertex 1 and 2 at indices 0 of array. Similarly, For vertex 1, it has two neighbour
(i.e, 2 and 0) So, insert vertices 2 and 0 at indices 1 of array. Similarly, for vertex 2, insert
its neighbours in array of list.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 13


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 2:

Let's see the adjacency list representation of an undirected graph.

 In the above figure, we can see that there is a linked list or adjacency list for every
node of the graph. From vertex A, there are paths to vertex B and vertex D. These
nodes are linked to nodes A in the given adjacency list.
 An adjacency list is maintained for each node present in the graph, which stores the
node value and a pointer to the next adjacent node to the respective node. If all the
adjacent nodes are traversed, then store the NULL in the pointer field of the last
node of the list.
 The sum of the lengths of adjacency lists is equal to twice the number of edges
present in an undirected graph.

Example 3:

We can represent this graph in the form of a linked list

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 14


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Here, 0, 1, 2, 3 are the vertices and each of them forms a linked list with all of its adjacent
vertices. For instance, vertex 1 has two adjacent vertices 0 and 2. Therefore, 1 is linked with
0 and 2 in the figure above.

Representation of Directed Graph to Adjacency list:


Example 1:
The below directed graph has 3 vertices. So, an array of list will be created of size 3, where
each indices represent the vertices. Now, vertex 0 has no neighbours. For vertex 1, it has two
neighbour (i.e, 0 and 2) So, insert vertices 0 and 2 at indices 1 of array. Similarly, for vertex
2, insert its neighbours in array of list.

Example 2:
the directed graph, and let's see the adjacency list representation of that graph.

For a directed graph, the sum of the lengths of adjacency lists is equal to the number of edges
present in the graph.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 15


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Representation of Weighted Directed Graph to Adjacency list:

The weighted directed graph, and let's see the adjacency list representation of that graph.
Example 1:

In the case of a weighted directed graph, each node contains an extra field that is called the
weight of the node.
In an adjacency list, it is easy to add a vertex. Because of using the linked list, it also saves
space.

Example 2:
In the adjacency list, each element in the list will have two values. The first one is the
destination node, and the second one is the weight between these two nodes.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 16


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

The representation is like below.

Example 3:

Example 4:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 17


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Adjacency Multi List

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 18


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Inverse Adjacency List:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 19


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 20


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

What is BFS?
BFS stands for Breadth First Search. It is also known as level order traversal. The Queue
data structure is used for the Breadth First Search traversal. When we use the BFS algorithm
for the traversal in a graph, we can consider any node as a root node.
Traversal means visiting all the nodes of a graph. Breadth First Traversal or Breadth First
Search is a recursive algorithm for searching all the vertices of a graph or tree data structure.

BFS algorithm
A standard BFS implementation puts each vertex of the graph into one of two categories:
1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The algorithm works as follows:
1. Start by putting any one of the graph's vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
back of the queue.
4. Keep repeating steps 2 and 3 until the queue is empty.
The graph might have two different disconnected parts so to make sure that we cover every
vertex, we can also run the BFS algorithm on every node

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 21


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

BFS example
Let's see how the Breadth First Search algorithm works with an example. We use an
undirected graph with 5 vertices.

We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all
its adjacent vertices in the stack.

Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back of the queue and
visit 3, which is at the front of the queue.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 22


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We
visit it.

Since the queue is empty, we have completed the Breadth First Traversal of the graph.
// BFS algorithm in C++

#include <iostream>

#include <list>

using namespace std;

class Graph {

int numVertices;

list<int>* adjLists;

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 23


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

bool* visited;

public:

Graph(int vertices);

void addEdge(int src, int dest);

void BFS(int startVertex);

};

// Create a graph with given vertices,

// and maintain an adjacency list

Graph::Graph(int vertices) {

numVertices = vertices;

adjLists = new list<int>[vertices];

// Add edges to the graph

void Graph::addEdge(int src, int dest) {

adjLists[src].push_back(dest);

adjLists[dest].push_back(src);

// BFS algorithm

void Graph::BFS(int startVertex) {

visited = new bool[numVertices];

for (int i = 0; i < numVertices; i++)

visited[i] = false;

list<int> queue;

visited[startVertex] = true;

queue.push_back(startVertex);

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 24


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

list<int>::iterator i;

while (!queue.empty()) {

int currVertex = queue.front();

cout << "Visited " << currVertex << " ";

queue.pop_front();

for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) {

int adjVertex = *i;

if (!visited[adjVertex]) {

visited[adjVertex] = true;

queue.push_back(adjVertex);

int main() {

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

g.BFS(2);

return 0;

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 25


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Application of BFS

 Finding the shortest path


 Minimum spanning tree for un-weighted graph
 GPS navigation system
 Detecting cycles in an undirected graph
 Finding all nodes within one connected component

What is DFS?
DFS stands for Depth First Search. In DFS traversal, the stack data structure is used, which
works on the LIFO (Last In First Out) principle. In DFS, traversing can be started from any
node, or we can say that any node can be considered as a root node until the root node is not
mentioned in the problem.
In the case of BFS, the element which is deleted from the Queue, the adjacent nodes of the
deleted node are added to the Queue. In contrast, in DFS, the element which is removed from
the stack, then only one adjacent node of a deleted node is added in the stack.

Let's consider the below graph for the Depth First Search traversal.

Consider node 0 as a root node.

First, we insert the element 0 in the stack as shown below:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 26


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

The node 0 has two adjacent nodes, i.e., 1 and 3. Now we can take only one adjacent node,
either 1 or 3, for traversing. Suppose we consider node 1; therefore, 1 is inserted in a stack
and gets printed as shown below:

Now we will look at the adjacent vertices of node 1. The unvisited adjacent vertices of node 1
are 3, 2, 5 and 6. We can consider any of these four vertices. Suppose we take node 3 and
insert it in the stack as shown below:

Consider the unvisited adjacent vertices of node 3. The unvisited adjacent vertices of
node 3 are 2 and 4. We can take either of the vertices, i.e., 2 or 4. Suppose we take
vertex 2 and insert it in the stack as shown below:

The unvisited adjacent vertices of node 2 are 5 and 4. We can choose either of the
vertices, i.e., 5 or 4. Suppose we take vertex 4 and insert in the stack as shown below:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 27


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Now we will consider the unvisited adjacent vertices of node 4. The unvisited
adjacent vertex of node 4 is node 6. Therefore, element 6 is inserted into the stack as
shown below:

After inserting element 6 in the stack, we will look at the unvisited adjacent vertices of node
6. As there is no unvisited adjacent vertices of node 6, so we cannot move beyond node 6. In
this case, we will perform backtracking. The topmost element, i.e., 6 would be popped out
from the stack as shown below:

The topmost element in the stack is 4. Since there are no unvisited adjacent vertices left of
node 4; therefore, node 4 is popped out from the stack as shown below:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 28


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

The next topmost element in the stack is 2. Now, we will look at the unvisited adjacent
vertices of node 2. Since only one unvisited node, i.e., 5 is left, so node 5 would be pushed
into the stack above 2 and gets printed as shown below:

Now we will check the adjacent vertices of node 5, which are still unvisited. Since there is no
vertex left to be visited, so we pop the element 5 from the stack as shown below:

We cannot move further 5, so we need to perform backtracking. In backtracking, the


topmost element would be popped out from the stack. The topmost element is 5 that would
be popped out from the stack, and we move back to node 2 as shown below:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 29


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

We will check the adjacent vertices of node 0, which are still unvisited. As there is no
adjacent vertex left to be visited, so we perform backtracking. In this, only one
element, i.e., 0 left in the stack, would be popped out from the stack as shown below:

Depth First Search traversal

Example2:

Depth First Search traversal : 1,2,4,5,6,3,7

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 30


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Differences between BFS and DFS


The following are the differences between the BFS and DFS:

BFS DFS

Full form BFS stands for Breadth First Search. DFS stands for Depth First Search.

Technique It a vertex-based technique to find It is an edge-based technique because the


the shortest path in a graph. vertices along the edge are explored first from
the starting to the end node.

Definition BFS is a traversal technique in which DFS is also a traversal technique in which
all the nodes of the same level are traversal is started from the root node and
explored first, and then we move to explore the nodes as far as possible until we
the next level. reach the node that has no unvisited adjacent
nodes.

Data Structure Queue data structure is used for the Stack data structure is used for the BFS traversal.
BFS traversal.

Backtracking BFS does not use the backtracking DFS uses backtracking to traverse all the
concept. unvisited nodes.

Number of BFS finds the shortest path having a In DFS, a greater number of edges are required
edges minimum number of edges to to traverse from the source vertex to the
traverse from the source to the destination vertex.
destination vertex.

Optimality BFS traversal is optimal for those DFS traversal is optimal for those graphs in which
vertices which are to be searched solutions are away from the source vertex.
closer to the source vertex.

Speed BFS is slower than DFS. DFS is faster than BFS.

Suitability for It is not suitable for the decision It is suitable for the decision tree. Based on the
decision tree tree because it requires exploring all decision, it explores all the paths. When the goal

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 31


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

the neighboring nodes first. is found, it stops its traversal.

Memory It is not memory efficient as it It is memory efficient as it requires less memory


efficient requires more memory than DFS. than BFS.

Spanning Tree
A spanning tree is a sub-graph of an undirected connected graph, which includes all the
vertices of the graph with a minimum possible number of edges. If a vertex is missed, then it
is not a spanning tree.
The edges may or may not have weights assigned to them.
The total number of spanning trees with n vertices that can be created from a complete graph
is equal to n(n-2).
If we have n = 4, the maximum number of possible spanning trees is equal to 4(4-2) = 16.
Thus, 16 spanning trees can be formed from a complete graph with 4 vertices.

Example of a Spanning Tree


Let's understand the spanning tree with examples below:
Let the original graph be:

Some of the possible spanning trees that can be created from the above graph are:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 32


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Spanning Tree Applications


 Computer Network Routing Protocol
 Cluster Analysis
 Civil Network Planning

Minimum Spanning Tree (MST)


A minimum spanning tree (MST) is defined as a spanning tree that has the minimum weight
among all the possible spanning trees
OR
A minimum spanning tree is a spanning tree in which the sum of the weight of the edges is as
minimum as possible.

Example of a Spanning Tree


Let's understand the above definition with the help of the example below.
The initial graph is:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 33


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

The possible spanning trees from the above graph are:

The minimum spanning tree from the above spanning trees is:

Example 2:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 34


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 3:
The minimum spanning tree is a spanning tree whose sum of the edges is minimum. Consider
the below graph that contains the edge weight:

The following are the spanning trees that we can make from the above graph.
 The first spanning tree is a tree in which we have removed the edge between the
vertices 1 and 5 shown as below:
The sum of the edges of the above tree is (1 + 4 + 5 + 2): 12
 The second spanning tree is a tree in which we have removed the edge between the
vertices 1 and 2 shown as below:
The sum of the edges of the above tree is (3 + 2 + 5 + 4) : 14
 The third spanning tree is a tree in which we have removed the edge between the
vertices 2 and 3 shown as below:
The sum of the edges of the above tree is (1 + 3 + 2 + 5) : 11
 The fourth spanning tree is a tree in which we have removed the edge between the
vertices 3 and 4 shown as below:
The sum of the edges of the above tree is (1 + 3 + 2 + 4) : 10. The edge cost 10 is
minimum so it is a minimum spanning tree.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 35


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Properties of a Spanning Tree:


The spanning tree holds the below-mentioned principles:
 The number of vertices (V) in the graph and the spanning tree is the same.
 There is a fixed number of edges in the spanning tree which is equal to one less than the
total number of vertices ( E = V-1 ).
 The spanning tree should not be disconnected, as in there should only be a single
source of component, not more than that.
 The spanning tree should be acyclic, which means there would not be any cycle in the
tree.
 The total cost (or weight) of the spanning tree is defined as the sum of the edge weights
of all the edges of the spanning tree.
 There can be many possible spanning trees for a graph.

Minimum Spanning tree Applications


 To find paths in the map
 To design networks like telecommunication networks, water supply networks, and electrical
grids.

(Greedy algorithms for computing minimum spanning tree- Prims and Kruskal Algorithms)

The minimum spanning tree from a graph is found using the following algorithms:
1. Prim's Algorithm
2. Kruskal's Algorithm

Prim's Algorithm
 Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree
from a graph. Prim's algorithm finds the subset of edges that includes every vertex of
the graph such that the sum of the weights of the edges can be minimized.
 Prim's algorithm starts with the single node and explores all the adjacent nodes with all
the connecting edges at every step. The edges with the minimal weights causing no
cycles in the graph got selected.

How does the prim's algorithm work?


Prim's algorithm is a greedy algorithm that starts from one vertex and continue to add the
edges with the smallest weight until the goal is reached. The steps to implement the prim's
algorithm are given as follows –
 First, we have to initialize an MST with the randomly chosen vertex.
 Now, we have to find all the edges that connect the tree in the above step with the new
vertices. From the edges found, select the minimum edge and add it to the tree.
 Repeat step 2 until the minimum spanning tree is formed.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 36


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example :

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 37


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 2:

Step 1 - First, we have to choose a vertex from the above graph. Let's choose B.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 38


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 2 - Now, we have to choose and add the shortest edge from vertex B. There are two
edges from vertex B that are B to C with weight 10 and edge B to D with weight 4. Among
the edges, the edge BD has the minimum weight. So, add it to the MST.

Step 3 - Now, again, choose the edge with the minimum weight among all the other edges. In
this case, the edges DE and CD are such edges. Add them to MST and explore the adjacent of
C, i.e., E and A. So, select the edge DE and add it to the MST.

Step 4 - Now, select the edge CD, and add it to the MST.

Step 5 - Now, choose the edge CA. Here, we cannot select the edge CE as it would create a
cycle to the graph. So, choose the edge CA and add it to the MST.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 39


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

So, the graph produced in step 5 is the minimum spanning tree of the given graph. The cost
of the MST is given below –

Cost of MST = 4 + 2 + 1 + 3 = 10 units.

The applications of prim's algorithm are -


 Prim's algorithm can be used in network designing.
 It can be used to make network cycles.
 It can also be used to lay down electrical wiring cables.

Dijkstra's Algorithm:
Dijkstra's Algorithm was designed and published by Dr. Edsger W. Dijkstra, a Dutch
Computer Scientist, Software Engineer, Programmer, Science Essayist, and Systems
Scientist.
Dijkstra's Algorithm is a Graph algorithm that finds the shortest path from a source
vertex to all other vertices in the Graph (single source shortest path). 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.
Algorithm
 Declare two arrays − distance[] to store the distances from the source vertex to the
other vertices in graph and visited[] to store the visited vertices.
 Set distance[S] to ‘0’ and distance[v] = ∞, where v represents all the other vertices in
the graph.
 Add S to the visited[] array and find the adjacent vertices of S with the minimum
distance.
 The adjacent vertex to S, say A, has the minimum distance and is not in the visited
array yet. A is picked and added to the visited array and the distance of A is changed
from ∞ to the assigned distance of A, say d1, where d1 < ∞.
 Repeat the process for the adjacent vertices of the visited vertices until the shortest
path spanning tree is formed.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 40


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 1
To understand the dijkstra’s concept better, let us analyze the algorithm with the help of an
example graph –

Step 1

Initialize the distances of all the vertices as ∞, except the source node S.

Vertex S A B C D E

Distance 0 ∞ ∞ ∞ ∞ ∞

Now that the source vertex S is visited, add it into the visited array.

visited = {S}

Step 2

The vertex S has three adjacent vertices with various distances and the vertex with minimum
distance among them all is A. Hence, A is visited and the dist[A] is changed from ∞ to 6.
The vertex S has three adjacent vertices with various distances and the vertex with minimum
distance among them all is A. Hence, A is visited and the dist[A] is changed from ∞ to 6.

S→A=6
S→D=8
S→E=7

Vertex S A B C D E

Distance 0 6 ∞ ∞ 8 7

Visited = {S, A}

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 41


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 3

There are two vertices visited in the visited array, therefore, the adjacent vertices must be
checked for both the visited vertices.
Vertex S has two more adjacent vertices to be visited yet: D and E. Vertex A has one adjacent
vertex B.
Calculate the distances from S to D, E, B and select the minimum distance −

S → D = 8 and S → E = 7.
S → B = S → A + A → B = 6 + 9 = 15

Vertex S A B C D E

Distance 0 6 15 ∞ 8 7

Visited = {S, A, E}

Step 4

Calculate the distances of the adjacent vertices – S, A, E – of all the visited arrays and select
the vertex with minimum distance.

S → D = 8
S → B = 15
S → C = S → E + E → C = 7 + 5 = 12

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 42


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Vertex S A B C D E

Distance 0 6 15 12 8 7

Visited = {S, A, E, D}

Step 5
Recalculate the distances of unvisited vertices and if the distances minimum than existing
distance is found, replace the value in the distance array.
S → C = S → E + E → C = 7 + 5 = 12
S → C = S → D + D → C = 8 + 3 = 11

dist[C] = minimum (12, 11) = 11

S → B = S → A + A → B = 6 + 9 = 15
S → B = S → D + D → C + C → B = 8 + 3 + 12 = 23

dist[B] = minimum (15,23) = 15

Vertex S A B C D E

Distance 0 6 15 11 8 7

Visited = { S, A, E, D, C}

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 43


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Applications of Dijkstra's Algorithm


Here are some of the common applications of Dijkstra's algorithm:
 In maps to get the shortest distance between locations. An example is Google Maps.
 In telecommunications to determine transmission rate.
 In robotic design to determine shortest path for automated robots.
Disadvantage of Dijkstra’s Algorithm
 It follows the blind search, so wastes a lot of time to give the desired output.
 It Negative edges value cannot be handled by it.
 We need to keep track of vertices that have been visited.

Step 6

The remaining unvisited vertex in the graph is B with the minimum distance 15, is added to
the output spanning tree.

Visited = {S, A, E, D, C, B}

The shortest path spanning tree is obtained as an output using the dijkstra’s algorithm.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 44


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 2:

Dijkstra’s Algorithm will generate the shortest path from Node 0 to all other Nodes in the
graph.

The algorithm will generate the shortest path from node 0 to all the other nodes in the
graph.
For this graph, we will assume that the weight of the edges represents the distance
between two nodes.
Initially we have a set of resources given below :
 The Distance from the source node to itself is 0. In this example the source node is 0.
 The distance from the source node to all other node is unknown so we mark all of them
as infinity.

Example: 0 -> 0, 1-> ∞,2-> ∞,3-> ∞,4-> ∞,5-> ∞,6-> ∞

 we’ll also have an array of unvisited elements that will keep track of unvisited or
unmarked Nodes.
 Algorithm will complete when all the nodes marked as visited and the distance between
them added to the path. Unvisited Nodes:- 0 1 2 3 4 5 6.

Step 1: Start from Node 0 and mark Node as visited as you can check in below image
visited Node is marked red.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 45


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 2: Check for adjacent Nodes, Now we have to choices (Either choose Node1 with
distance 2 or either choose Node 2 with distance 6 ) and choose Node with minimum
distance. In this step Node 1 is Minimum distance adjacent Node, so marked it as visited
and add up the distance.
Distance: Node 0 -> Node 1 = 2

Step 3: Then Move Forward and check for adjacent Node which is Node 3, so marked it as
visited and add up the distance, Now the distance will be:

Distance: Node 0 -> Node 1 -> Node 3 = 2 + 5 = 7

Step 4: Again we have two choices for adjacent Nodes (Either we can choose Node 4 with
distance 10 or either we can choose Node 5 with distance 15) so choose Node with
minimum distance. In this step Node 4 is Minimum distance adjacent Node, so marked it as
visited and add up the distance.

Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 = 2 + 5 + 10 = 17

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 46


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 5: Again, Move Forward and check for adjacent Node which is Node 6, so marked it
as visited and add up the distance, Now the distance will be:

Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 -> Node 6 = 2 + 5 + 10 + 2 = 19

So, the Shortest Distance from the Source Vertex is 19 which is optimal one

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 47


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 3: Let us now understand the implementation of the algorithm with the help of an
example:

The Given 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.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 48


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Hence, the final paths we concluded are:


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)

Solve below examples by using Dikjtra's Single source shortest path


1)

2)

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 49


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

3)

All pairs shortest paths- Flyod-Warshall Algorithm Topological ordering

Flyod-Warshall Algorithm
The Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen
Warshall, is a fundamental algorithm in computer science and graph theory. It is used to
find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is
highly efficient and can handle graphs with both positive and negative edge weights,
making it a versatile tool for solving a wide range of network and connectivity problems.

The Floyd Warshall Algorithm is an all pair shortest path algorithm


unlike Dijkstra and Bellman Ford which are single source shortest path algorithms.This
algorithm works for both the directed and undirected weighted graphs. But, it does not
work for the graphs with negative cycles (where the sum of the edges in a cycle is
negative). It follows Dynamic Programming approach to check every possible path going
via every possible node in order to calculate shortest distance between every pair of nodes.

 Floyd Warshall Algorithm is a famous algorithm.


 It is used to solve All Pairs Shortest Path Problem.
 It computes the shortest path between every pair of vertices of the given graph.
 Floyd Warshall Algorithm is an example of dynamic programming approach.

When Floyd Warshall Algorithm Is Used?


Floyd Warshall Algorithm is best suited for dense graphs.
 This is because its complexity depends only on the number of vertices in the given
graph.
 For sparse graphs, Johnson’s Algorithm is more suitable.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 50


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 1:
Consider the following directed weighted graph-

Using Floyd Warshall Algorithm, find the shortest path distance between every pair of
vertices.
Solution-
Step-01:
 Remove all the self loops and parallel edges (keeping the lowest weight edge) from
the graph.
 In the given graph, there are neither self edges nor parallel edges.

Step-02:
Write the initial distance matrix.
 Itrepresents the distance between every pair of vertices in the form of given weights.
 For diagonal elements (representing self-loops), distance value = 0.
 For vertices having a direct edge between them, distance value = weight of that edge.
 For vertices having no direct edge between them, distance value = ∞.
Initial distance matrix for the given graph is-

step-03:
Using Floyd Warshall Algorithm, write the following 4 matrices-

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 51


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 52


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 2:

Calculate the distance from the source vertex to destination vertex through this vertex k

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 53


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Calculate the distance from the source vertex to destination vertex through this vertex 2

Similarly, A3 and A4 is also created

Calculate the distance from the source vertex to destination vertex through this vertex 3

Calculate the distance from the source vertex to destination vertex through this vertex 4

A4 gives the shortest path between each pair of vertices.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 54


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Example 3:

Example 4:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 55


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

After the fourth iteration, we have got the shortest path between every pair of vertices in the
graph. For example, the shortest path from vertex A to vertex D is 4, which is the value in the
matrix at row A and column D.

Example 5:

Step 1: Initialize the Distance[][] matrix using the input graph such that Distance[i][j]=
weight of edge from i to j, also Distance[i][j] = Infinity if there is no edge from i to j.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 56


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 2: Treat node A as an intermediate node and calculate the Distance[][] for
every {i,j} node pair using the formula:

Step 3: Treat node B as an intermediate node and calculate the Distance[][] for
every {i,j} node pair using the formula:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 57


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 4: Treat node C as an intermediate node and calculate the Distance[][] for
every {i,j} node pair using the formula:

Step 5: Treat node D as an intermediate node and calculate the Distance[][] for
every {i,j} node pair using the formula:

Step 6: Treat node E as an intermediate node and calculate the Distance[][] for
every {i,j} node pair using the formula:

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 58


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Step 7: Since all the nodes have been treated as an intermediate node, we can now
return the updated Distance[][] matrix as our answer matrix.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 59


© Copyright 2023-2024 www.javatpoint.com.
DSA UNIT 3 GRAPH

Topological Sort-
Topological Sort is a linear ordering of the vertices in such a way that if there is an edge in
the DAG going from vertex ‘u’ to vertex ‘v’, then ‘u’ comes before ‘v’ in the ordering.
It is important to note that-
 Topological Sorting is possible if and only if the graph is a Directed Acyclic Graph.
 There may exist multiple different topological orderings for a given directed acyclic
graph.

Subject Teacher : Ms. Atole S. M. 210252: Data Structures and Algorithms 60


© Copyright 2023-2024 www.javatpoint.com.

You might also like