Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Unit-4 Graphs Notes

Topic in ADA

Uploaded by

Anshul Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit-4 Graphs Notes

Topic in ADA

Uploaded by

Anshul Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit -4

Graphs

What is Graph Data Structure?

A Graph is a non-linear data structure consisting of vertices and edges. The vertices are
sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in
the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ).
The graph is denoted by G(E, V).

Figure 1: Graph

Components of a Graph
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as
vertex or nodes. Every node/vertex can be labeled or unlabelled.

Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of
nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no
rules. Sometimes, edges are also known as arcs. Every edge can be labeled/unlabelled.
Graphs are used to solve many real-life problems. Graphs are used to represent networks. The
networks may include paths in a city or telephone network or circuit network. Graphs are also
used in social networks like linkedIn, Facebook. For example, in Facebook, each person is
represented with a vertex(or node). Each node is a structure and contains information like person
id, name, gender, locale etc.

Types of Graph

Page 1 of 35
Directed Graph
A directed graph is a set of vertices (nodes) connected by edges, with each node having a
direction associated with it.

Edges are usually represented by arrows pointing in the direction the graph can be traversed.

In the below example, the graph can be traversed from vertex A to B, but not from vertex B to A.

A B

Examples of Directed Graph:

Set of Vertices (V)={0,1,2,3,4}

Set of Edges (E)={(0,1), (0,2), (0,3), (1,3), (1,4), (2,3), (3,4)}

Characteristics of Directed Graph


Directed graphs have several characteristics that make them different from undirected graphs.
Here are some key characteristics of directed graphs:

● Directed edges: In a directed graph, edges have a direction associated with them,
indicating a one-way relationship between vertices.

Page 2 of 35
● Indegree and Outdegree: Each vertex in a directed graph has two different degree
measures: indegree and outdegree. Indegree is the number of incoming edges to a vertex,
while outdegree is the number of outgoing edges from a vertex.
● Cycles: A directed graph can contain cycles, which are paths that start and end at the
same vertex and contain at least one edge. Cycles can be important for understanding
feedback loops or other patterns in the graph.
● Paths and reachability: Paths in a directed graph follow the direction of the edges, and
can be used to analyze reachability between vertices.

Applications of Directed Graph


Directed graphs have many applications across a wide range of fields. Here are some examples:

● Social networks: Social networks are often modeled as directed graphs, where each
person is a vertex and relationships such as friendships or following are represented as
edges.
● Transportation networks: Transportation systems such as roads, airports, or subway
systems can be modeled as directed graphs, with vertices representing locations and
edges representing connections between them.
● Computer networks: Computer networks such as the internet can be represented as
directed graphs, with vertices representing devices such as computers or routers and
edges representing connections between them.
● Project management: Project management can be modeled as a directed graph, with
vertices representing tasks and edges representing dependencies between them.

Advantages of Directed Graph

● Can model complex relationships: Directed graphs are useful for modeling complex
relationships where directionality is important, such as social networks or transportation
systems.
● Can be used for analysis: Directed graphs allow for analysis of the flow of relationships
or information in a system, which can be useful for optimization or understanding of the
system’s behavior.
● Can represent dependencies: Directed graphs are useful for representing dependencies
between entities, such as in project management or recommender systems.

Disadvantages of Directed Graph

● May be more complex: Directed graphs can be more complex than undirected graphs,
since each edge has a direction associated with it.

Page 3 of 35
● May require more processing power: Analyzing directed graphs may require more
processing power than analyzing undirected graphs, since the directionality of the edges
must be taken into account.
● Maybe less intuitive: Since directed graphs are less common than undirected graphs, they
may be less intuitive for people to work with or understand.

Undirected Graph

In an undirected graph the edges are bidirectional, with no direction associated with them.
Hence, the graph can be traversed in either direction. The absence of an arrow tells us that the
graph is undirected.

In the below example, the graph can be traversed from node A to B as well as from node B to A.

A B

Examples of Undirected Graph

Set of Vertices (V)= {0, 1, 2, 3, 4}

Set of Edges (E)= {{0,1}, {0,2}, {0,3}, {1,0},{1,3},{1,4}, {2,0},{2,3}, {3,0},{3,1},{3,2},{3,4},


{4,1},{4,3}}

Characteristics of an Undirected Graph


● Edges in an undirected graph are bidirectional in nature.

Page 4 of 35
● In an undirected graph, there is no concept of a “parent” or “child” vertex as there is no
direction to the edges.
● An undirected graph may contain loops, which are edges that connect a vertex to itself.
● Degree of each vertex is the same as the total number of edges connected to it.

Applications of Undirected Graph


● Social Networks: Undirected graphs are used to model social networks where people are
represented by nodes and the connections between them are represented by edges.
● Traffic flow optimization: Undirected graphs are used in traffic flow optimization to
model the flow of vehicles on road networks. The vertices of the graph represent
intersections or road segments, and the edges represent the connections between them.
The graph can be used to optimize traffic flow and plan transportation infrastructure.
● Website analysis: Undirected graphs can be used to analyze the links between web pages
on the internet. Each web page is represented by a vertex, and each link between web
pages is represented by an edge.

Advantages of Undirected Graph


● It provides simplicity as they are basic and easy to grasp, making them valuable for
representing a wide range of real-world systems.
● It provides flexibility as they are versatile and may be used to describe a broad range of
systems.

Disadvantages of Undirected Graph


● It may be undesirable for some applications that need directionality due to their lack of
directionality.
● It provides limited information, In some cases, it may not give enough information about
certain systems since they merely capture the existence or absence of edges.

Write the difference between Directed Graph and Undirected Graph?

1. Edge Direction:
○ Directed Graph (Digraph): Edges have a direction, indicating a one-way
relationship from one node to another.
○ Undirected Graph: Edges have no direction, representing a mutual relationship
between nodes.
2. Symmetry:
○ Directed Graph: Edges can be asymmetric, meaning there might not be a
corresponding edge in the opposite direction.
○ Undirected Graph: Edges are symmetric, implying a bidirectional relationship
between connected nodes.

Page 5 of 35
3. Edge Representation:
○ Directed Graph: Edges are represented as ordered pairs (u, v), where u is the
source node, and v is the target node.
○ Undirected Graph: Edges are represented as unordered pairs {u, v} or (u, v).
4. Adjacency Matrix:
○ Directed Graph: The adjacency matrix is not necessarily symmetric, with A[i][j]
indicating an edge from node i to node j.
○ Undirected Graph: The adjacency matrix is always symmetric, with A[i][j] equal
to A[j][i] for an edge between nodes i and j.
5. Degree:
○ Directed Graph: Nodes have both in-degree (incoming edges) and out-degree
(outgoing edges).
○ Undirected Graph: Nodes have a degree, representing the total number of edges
incident to the node.
6. Use Cases:
○ Directed Graph: Models relationships with directionality, such as dependencies,
processes, and flows.
○ Undirected Graph: Models symmetric relationships, like friendships, connections,
or associations.
7. Cycles:
○ Directed Graph: Can have directed cycles, where a sequence of edges forms a
closed loop with consistent directions.
○ Undirected Graph: Can have undirected cycles, where a sequence of edges forms
a closed loop without considering direction.

The following are additional terms connected to graph theory:

Paths:

Definition: A path in a graph is a sequence of vertices where each adjacent pair is


connected by an edge. The length of a path is the number of edges in it.

Simple Path: A path in which no vertex is repeated. In the graph A -> B -> C, the
sequence A -> B -> C is a path.

Example:.

Page 6 of 35
In this graph:

● Vertices: A, B, C, D, E
● Directed Edges: A->B, B->C, C->E, E->D, D->A, E->A

Now, let's consider some paths:

1. Path from A to C: A B C
2. Path from B to D:B C E D
3. Path from E to A: E D A
4. Path from C to E: C E
5. Path from D to B: D A B

For example, suppose we wish to reach from node A to node E.

In this graph:

the possible paths are: A→C→E or A→B→C→E.

Page 7 of 35
Cycles:

Definition: A cycle in a graph is a path that starts and ends at the same vertex, and no
other vertex is repeated in the path.

Simple Cycle: A cycle in which the only repeated vertex is the starting and ending
vertex.

Example: In the graph A -> B -> C -> A, the sequence A -> B -> C -> A forms a cycle.

For Example, The directed graph that represents the cycle A -> B -> C -> A can be
illustrated as follows:

A B

In this graph:

● Vertices: A, B, C
● Directed Edges: A -> B, B -> C, C -> A

The cycle A -> B -> C -> A is formed by following the arrows from A to B, B to C, and
C back to A, creating a closed loop. Each arrow represents a directed edge in the graph.

What is Spanning tree?

A spanning tree is a sub-graph of an undirected connected graph G, 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. A spanning tree does not have cycles and it cannot be disconnected.

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

Page 8 of 35
If we have n = 4, the maximum number of possible spanning trees is equal to 44-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:

Original Graph

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

A Spanning Tree

A Spanning Tree

Page 9 of 35
A Spanning Tree

A Spanning Tree

A Spanning Tree

A Spanning Tree

Page 10 of 35
General Properties of Spanning Tree

Following are a few properties of the spanning tree connected to graph G –

 A connected graph can have multiple spanning trees. A graph with n vertices can have an
n(n-2) number of spanning trees.
 Spanning trees does not have any loop or cycle.
 Spanning trees have n vertices and n-1 number of edges.
 All spanning tree of a graph has equivalent vertices.
 Removing a single edge from the spanning tree will make the graph disconnected as the
spanning tree is minimal connected.
 Adding any edge can create a loop or cycle in the spanning tree.
 Spanning trees can be formed on connected graphs only, disconnected graphs cannot
form spanning trees.

Applications of Spanning Tree:

 In routing protocols
 Cluster mapping and analysis
 Network Planning
 Explore the path/ route in the maps.

Minimum Spanning Tree

A minimum spanning tree or minimum cost spanning tree is that spanning tree, which covers all
the vertices of the graph with minimum edges and the sum of the weight of those edges is
minimum among other spanning trees of that graph.

Example of a Spanning Tree

Let's understand the above definition with the help of the example below.

The initial graph is:

Page 11 of 35
Weighted Graph

The possible spanning trees from the above graph are:

1st Minimum Spanning Tree

2nd Minimum Spanning Tree

3rd Minimum Spanning Tree

Page 12 of 35
4th Minimum Spanning Tree

The minimum spanning tree from the above spanning trees is:

Minimum Spanning tree Applications

 To find paths in the map


 To design networks like telecommunication networks, water supply networks, and
electrical grids.

Page 13 of 35
The minimum spanning tree from a graph is found using the following algorithms:

1. Prim's Algorithm
2. Kruskal's Algorithm

1. 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 (Minimum Spanning Tree) 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.

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.

Example of prim's algorithm

Now, let's see the working of prim's algorithm using an example. It will be easier to understand
the prim's algorithm using an example.

Suppose, a weighted graph is –

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

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.

Page 15 of 35
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.

Page 16 of 35
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.
Algorithm
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe vertices
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum
weight
Step 4: Add the selected edge and the vertex to the minimum spanning tree T
[END OF LOOP]
Step 5: EXIT
2. Kruskal's Algorithm

Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted
graph. The main target of the algorithm is to find the subset of edges by using which we
can traverse every vertex of the graph. It follows the greedy approach that finds an
optimum solution at every stage instead of focusing on a global optimum.

How does Kruskal's algorithm work?

In Kruskal's algorithm, we start from edges with the lowest weight and keep adding the
edges until the goal is reached. The steps to implement Kruskal's algorithm are listed as
follows –

 First, sort all the edges from low weight to high.


 Now, take the edge with the lowest weight and add it to the spanning tree. If the
edge to be added creates a cycle, then reject the edge.
 Continue to add the edges until we reach all vertices, and a minimum spanning
tree is created.
The applications of Kruskal's algorithm are –
 Kruskal's algorithm can be used to layout electrical wiring among cities.
 It can be used to lay down LAN connections.

Example of Kruskal's algorithm


Now, let's see the working of Kruskal's algorithm using an example. It will be easier to
understand Kruskal's algorithm using an example.
Suppose, a weighted graph is –

Page 17 of 35
The weight of the edges of the above graph is given in the below table –

Now, sort the edges given above in the ascending order of their weights.

Now, let's start constructing the minimum spanning tree.


Step 1 - First, add the edge AB with weight 1 to the MST.

Step 2 - Add the edge DE with weight 2 to the MST as it is not creating the cycle.

Page 18 of 35
Step 3 - Add the edge BC with weight 3 to the MST, as it is not creating any cycle or loop.

Step 4 - Now, pick the edge CD with weight 4 to the MST, as it is not forming the cycle.

Step 5 - After that, pick the edge AE with weight 5. Including this edge will create the cycle, so
discard it.
Step 6 - Pick the edge AC with weight 7. Including this edge will create the cycle, so discard it.
Step 7 - Pick the edge AD with weight 10. Including this edge will also create the cycle, so
discard it.

Page 19 of 35
So, the final minimum spanning tree obtained from the given weighted graph by using Kruskal's
algorithm is –

The cost of the MST is = AB + DE + BC + CD = 1 + 2 + 3 + 4 = 10.


Now, the number of edges in the above tree equals the number of vertices minus 1. So, the
algorithm stops here.
Algorithm
Step 1: Create a forest F in such a way that every vertex of the graph is a separate tree.
Step 2: Create a set E that contains all the edges of the graph.
Step 3: Repeat Steps 4 and 5 while E is NOT EMPTY and F is not spanning
Step 4: Remove an edge from E with minimum weight
Step 5: IF the edge obtained in Step 4 connects two different trees, then add it to the forest F
(for combining two trees into one tree).
ELSE
Discard the edge
Step 6: END
Complexity of Kruskal's algorithm
Now, let's see the time complexity of Kruskal's algorithm.
 Time Complexity
The time complexity of Kruskal's algorithm is O(E logE) or O(V logV), where E is the
no. of edges, and V is the no. of vertices.

Dijkstra’s Algorithm
Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest path
problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance
Page 20 of 35
between two vertices on a graph. It was conceived by Dutch computer scientist Edsger W.
Dijkstra in 1956.
The algorithm maintains a set of visited vertices and a set of unvisited vertices. It starts at the
source vertex and iteratively selects the unvisited vertex with the smallest tentative distance from
the source. It then visits the neighbours of this vertex and updates their tentative distances if a
shorter path is found. This process continues until the destination vertex is reached, or all
reachable vertices have been visited.
Need for Dijkstra’s Algorithm
The need for Dijkstra’s algorithm arises in many applications where finding the shortest path
between two points is crucial.

For example, It can be used in the routing protocols for computer networks and also used by map
systems to find the shortest path between starting point and the Destination.

Can Dijkstra’s Algorithm work on both Directed and Undirected graphs?


Yes, Dijkstra’s algorithm can work on both directed graphs and undirected graphs as this
algorithm is designed to work on any type of graph as long as it meets the requirements of
having non-negative edge weights and being connected.
In a directed graph, each edge has a direction, indicating the direction of travel between the
vertices connected by the edge. In this case, the algorithm follows the direction of the edges
when searching for the shortest path.
In an undirected graph, the edges have no direction, and the algorithm can traverse both forward
and backward along the edges when searching for the shortest path.

Algorithm for Dijkstra’s Algorithm:

1. The very first step is to mark all nodes as unvisited,


2. Mark the picked starting node with a current distance of 0 and the rest nodes with
infinity,
3. Now, fix the starting node as the current node,
4. For the current node, analyse all of its unvisited neighbours and measure their distances
by adding the current distance of the current node to the weight of the edge that connects
the neighbour node and current node,

Page 21 of 35
5. Compare the recently measured distance with the current distance assigned to the
neighbouring node and make it as the new current distance of the neighbouring node,
6. After that, consider all of the unvisited neighbours of the current node, mark the current
node as visited,
7. If the destination node has been marked visited then stop, an algorithm has ended, and
8. Else, choose the unvisited node that is marked with the least distance, fix it as the new
current node, and repeat the process again from step 4.

Dijkstra's Algorithm Applications

 To find the shortest path


 In social networking applications
 In a telephone network
 To find the locations in the map

Let’s try and understand the working of this algorithm using the following example-

Step 1

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

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

Page 22 of 35
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.

Visited = {S, A}

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 –

Page 23 of 35
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.

Visited = {S, A, E, D}

Page 24 of 35
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.

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

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

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

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}

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

Question: Using Dijkstra's algorithm, find out the shortest distance from the source vertex 's' to
the rest of the vertices in the given graph. Also write the order in which all the vertices of the
graph are visited.

Solution and Answer:

Page 26 of 35
Dijkstra's algorithm Solution for given problem

Dijkstra's Algorithm Complexity

Time Complexity: O(E Log V)

where, E is the number of edges and V is the number of vertices.

Space Complexity: O(V)

Some Advantages of Dijkstra’s Algorithm

 It has a linear time complexity so it can be easily used for large problems.
 It is useful in finding the shortest distance, so it is also used in google maps and
calculating traffic.
 It has its use in areas such as telephone networks and geographical maps.

Some Disadvantages of Dijkstra’s Algorithm

 It is unable to handle negative weights..


 It does an obscured exploration that consumes a lot of time while processing.
 As it heads to the acyclic graph, so can’t achieve the accurate shortest path.

Page 27 of 35
Directed Acyclic Graphs (DAG)

Definition: A Directed Acyclic Graph (DAG) is a type of graph that is directed, meaning that
edges have a direction (they go from one vertex to another), and it is acyclic, meaning that there
are no cycles or loops in the graph. In other words, you cannot start at a vertex and follow a
sequence of directed edges to return to the same vertex. Examples:

Directed Acyclic Graphs (DAGs) have several interesting and useful properties

1. Acyclic Nature: As the name suggests, DAGs do not contain any cycles. This property
simplifies various algorithms and analyses that involve traversing the graph.
2. Topological Ordering: A DAG can be topologically sorted, which means the vertices
can be linearly ordered in such a way that if there is a directed edge from vertex A to
vertex B, then A comes before B in the order. This topological ordering is unique for
DAGs and has applications in scheduling and task sequencing.
3. Unique Source and Sink: A DAG typically has a unique source (a vertex with no
incoming edges) and a unique sink (a vertex with no outgoing edges). These vertices play
significant roles in certain applications, such as task scheduling.
4. No Multiple Edges: In a DAG, there are no multiple edges between the same pair of
vertices. Each directed edge represents a unique relationship from one vertex to another.
5. Dependency Structure: DAGs are often used to model dependencies between entities.
For example, in project management, vertices may represent tasks, and directed edges
represent task dependencies, ensuring that tasks are completed in a specific order.
6. Efficient Reachability Testing: Due to the acyclic nature of DAGs, reachability testing
becomes more straightforward. It is easy to determine if there is a path from one vertex to
another without the risk of going in circles.
7. Efficient Shortest Path Algorithms: Algorithms for finding shortest paths, such as
Dijkstra's algorithm, work efficiently on DAGs. This is because the absence of cycles
ensures that the algorithm can make local greedy choices without revisiting already
explored vertices.

Page 28 of 35
8. Efficient Dynamic Programming: DAGs often lend themselves well to dynamic
programming techniques. Problems that exhibit optimal substructure and overlapping
subproblems can be efficiently solved using dynamic programming on a DAG.

Directed Acyclic Graphs have numerous applications in various fields, such as:

 Dependency Analysis: DAGs are often used to model dependencies between tasks or
events. In this context, a directed edge represents a dependency relationship, and the
absence of cycles ensures that there are no circular dependencies.
 Job Scheduling: DAGs are used in scheduling tasks or jobs where certain tasks must be
completed before others can start.
 Compiler Optimization: DAGs are employed in compilers for optimizing code,
particularly in the context of data flow analysis.
 Network Routing: In communication networks, DAGs can represent the flow of data or
information, ensuring efficient and directed communication paths.

Topological Sorting

A topological sort or topological ordering of a directed graph is a linear ordering of its vertices in
which u occurs before v in the ordering for every directed edge uv from vertex u to vertex v. For
example, the graph's vertices could represent jobs to be completed, and the edges could reflect
requirements that one work must be completed before another.

In this case, a topological ordering is just a legitimate task sequence. A topological sort is a
graph traversal in which each node v is only visited after all of its dependencies have been
visited. If the graph contains no directed cycles, then it is a directed acyclic graph. Any DAG has
at least one topological ordering, and there exist techniques for building topological orderings in
linear time for any DAG.

Some Applications of Topological Sorting

 Task Scheduling: In project management and task scheduling, topological sorting can be
used to schedule tasks that have dependencies on each other. Each task represents a
vertex, and the directed edges indicate dependencies. By performing a topological sort,
you can determine a valid order in which tasks can be executed.
 Dependency resolution: Topological sorting can be used to resolve dependencies
between different modules of a software project. For example, if a module depends on

Page 29 of 35
another module, topological sorting can be used to determine the order in which the
modules should be built.
 Deadlock detection: Topological sorting can be used to detect deadlocks in operating
systems. Deadlock is a state in which a process is waiting for a resource that is held by
another process, which is also waiting for a resource held by the first process.
Topological sorting can be used to detect such situations.
 Course scheduling: Topological sorting can be used to schedule courses in a university.
For example, if a course has prerequisites, topological sorting can be used to schedule the
courses in the correct order.
 Data serialization: Topological sorting can be used to serialize data structures. For
example, if a data structure contains references to other data structures, topological
sorting can be used to serialize the data structure in the correct order.
 Sentence ordering: Topological sorting can be used to order sentences in a document.
For example, if a document contains sentences that depend on other sentences,
topological sorting can be used to order the sentences in the correct order.
 Compiler Optimization: During the compilation of programming code, topological
sorting is used to optimize the order in which functions or procedures are compiled,
taking into account dependencies between them.
 Network Routing: In computer networks, topological sorting can be applied to
determine the optimal order for routing information through a network, considering
dependencies between different components.

Advantages of the Topological Sort

1. Efficient ordering: Topological sorting provides an efficient way to order the vertices of
a directed acyclic graph (DAG) in a way that respects their dependencies.
2. Easy implementation: Topological sorting can be implemented using adjacency lists,
which makes it easy to implement and understand.
3. Wide range of applications: Topological sorting has a wide range of applications in
different domains such as scheduling jobs, dependency resolution, deadlock detection,
course scheduling, critical path analysis, data serialization, and sentence ordering.
4. Low time and space complexity: The time and space complexity of topological sorting
is O(V+E), where V is the number of vertices and E is the number of edges in the graph.
5. Scalability for large-scale data processing: Topological sorting can be used for large-
scale data processing, making it a valuable tool for big data applications.

Page 30 of 35
Disadvantages of Topological Sorting

1. Topological sorting only works on directed acyclic graphs (DAGs) and cannot handle
cyclic graphs.
2. It does not provide a unique solution if there are multiple valid orders for the nodes.
3. It may not be the best algorithm for certain graph-related problems, depending on the
specific requirements and constraints.
4. The technique can be more complex to implement when compared to other techniques
like divide-and-conquer, and may require more careful planning

Algorithm of Topological Sorting

1. Create a stack to store the nodes.

2. Initialize a visited array of size N to keep the record of visited nodes.

3. Run a loop from 0 till N:

 If the node is not marked True in visited array, then call the recursive function for

topological sort and perform the following steps:

 Mark the current node as True in the visited array.

 Run a loop on all the nodes which has a directed edge to the current node.

 If the node is not marked True in the visited array, then recursively call the

topological sort function on the node.

 Push the current node in the stack.

4. Print all the elements in the stack.

Examples:

Consider the following directed acyclic graph-

Page 31 of 35
For this graph, following 4 different topological orderings are possible-

 123456

 123465

 132456

 132465

Problem:

Find the number of different topological orderings possible for the given graph-

Solution-

Page 32 of 35
Step-01:

Write in-degree of each vertex-

Step-02:

 Vertex-A has the least in-degree.


 So, remove vertex-A and its associated edges.
 Now, update the in-degree of other vertices.

Page 33 of 35
Step-03:

 Vertex-B has the least in-degree.


 So, remove vertex-B and its associated edges.
 Now, update the in-degree of other vertices.

Step-04:

There are two vertices with the least in-degree. So, following 2 cases are possible-

In case-01,

 Remove vertex-C and its associated edges.


 Then, update the in-degree of other vertices.

In case-02,

 Remove vertex-D and its associated edges.


 Then, update the in-degree of other vertices

Page 34 of 35
Step-05:

Now, the above two cases are continued separately in the similar manner.

In case-01,

 Remove vertex-D since it has the least in-degree.


 Then, remove the remaining vertex-E.

In case-02,

 Remove vertex-C since it has the least in-degree.


 Then, remove the remaining vertex-E.

Conclusion-

For the given graph, following 2 different topological orderings are possible-

 ABCDE
 ABDCE

Topological Sort Time Complexity

The time complexity of topological sort using Kahn’s algorithm is O(V+E), where V = Vertices,
E = Edges.

Topological Sort Space Complexity

Auxiliary space required is O(V).

***

Page 35 of 35

You might also like