Home » AKTU CSE Notes » AKTU Data Structure Unit 4 Notes KCS 301

AKTU Data Structure Unit 4 Notes KCS 301

Last updated:

Support this post with a reaction:

4,676 views

Graphs are important non-linear data structures used to represent relationships and connections between different objects. A graph consists of a collection of vertices (nodes) and edges (connections) that link pairs of vertices.

Graphs are widely used in computer science to represent real-world networks such as social networks, computer networks, transportation systems, and web page connections. Unlike linear data structures such as arrays, stacks, and queues, graphs allow data elements to be connected in multiple ways without following a sequential order.

In this unit, we study the fundamental concepts of graphs, different graph representations such as Adjacency Matrix and Adjacency List, and graph traversal techniques such as Depth First Search (DFS) and Breadth First Search (BFS). We also cover Connected Components, Spanning Trees, Minimum Cost Spanning Trees using Prim’s and Kruskal’s algorithms, Transitive Closure using Warshall’s Algorithm, and Shortest Path using Dijkstra’s Algorithm.

AKTU Data Structure UNIT 4 Syllabus

Graphs: Terminology used with Graph, Data Structure for Graph Representations: Adjacency Matrices, Adjacency List, djacency.

Graph Traversal: Depth First Search and Breadth First Search, Connected Component, Spanning Trees, Minimum Cost Spanning Trees: Prims and 08 Kruskal algorithm. Transitive Closure and Shortest Path algorithm: Warshal Algorithm and Dijikstra Algorithm.

Graph Fundamentals

A Graph is a non-linear data structure used to represent relationships and connections between different objects. It consists of a collection of vertices (nodes) and edges (connections) that link pairs of vertices. Each vertex represents an individual object, while each edge represents a relationship or connection between two vertices.

Unlike linear data structures such as arrays, linked lists, and stacks, where elements are arranged in a sequential order, graphs allow elements to be connected in multiple ways. This makes graphs useful for representing complex relationships and networks.

Graphs are widely used in real-world applications such as social networks, computer networks, road maps, transportation systems, and web page links.

Graph Data Structure

A graph is mathematically represented as:

G=(V,E) G=(V,E)

Where:

  • (G) = Graph
  • (V) = Set of vertices
  • (E) = Set of edges

Graphs are used to represent relationships between objects.

Graph Terminology

TermDefinition
VertexA node in a graph
EdgeA connection between two vertices
Adjacent VerticesTwo vertices connected by an edge
Incident EdgeAn edge connected to a particular vertex
DegreeNumber of edges connected to a vertex
In-degreeNumber of incoming edges
Out-degreeNumber of outgoing edges
PathSequence of vertices connected by edges
CycleA path that starts and ends at the same vertex
Simple GraphA graph without self-loops or multiple edges
Connected GraphA graph in which every vertex is reachable from every other vertex
Disconnected GraphA graph containing vertices that cannot reach other vertices
Weighted GraphA graph whose edges have weights or costs
Unweighted GraphA graph whose edges have no weights
Directed GraphA graph with edges having directions
Undirected GraphA graph with edges having no directions
Self-loopAn edge connecting a vertex to itself
SubgraphA graph formed from a subset of vertices and edges
Complete GraphA graph in which every pair of distinct vertices is connected

Degree of a Vertex

The degree of a vertex is the total number of edges connected to that vertex. It indicates how many connections a vertex has with other vertices in a graph.

For an undirected graph:

deg⁡(v)=Number of edges connected to v\deg(v)=\text{Number of edges connected to }v

For a directed graph:

  • In-degree: The in-degree of a vertex is the total number of directed edges coming into that vertex from other vertices. It represents how many incoming connections a vertex receives.
  • Out-degree: The out-degree of a vertex is the total number of directed edges going out of that vertex towards other vertices. It represents how many outgoing connections a vertex makes.

Types of Graphs

Graph TypeDescription
Directed GraphEdges have directions
Undirected GraphEdges do not have directions
Weighted GraphEdges contain numerical weights
Unweighted GraphEdges do not contain weights
Connected GraphAll vertices are reachable
Complete GraphEvery vertex is connected to every other vertex
Cyclic GraphContains at least one cycle
Acyclic GraphContains no cycles
DAGDirected Acyclic Graph

Properties of a Complete Graph

For a complete undirected graph with (n) vertices:

E=n(n−1)2 E=\frac{n(n-1)}{2}

For example, for 4 vertices:

E=4(4−1)2=6 E=\frac{4(4-1)}{2}=6

Graph Representation

Graph representation refers to the method of storing vertices and edges of a graph in computer memory. It helps in performing graph operations such as searching, traversal, and checking connections between vertices.

There are two commonly used methods for representing a graph:

  1. Adjacency Matrix: Represents a graph using a two-dimensional array (matrix) that stores the connections between vertices.
  2. Adjacency List: Represents a graph using a list for each vertex, containing all the vertices directly connected to it.

Types of Graph Representation

1. Adjacency Matrix

An Adjacency Matrix is a graph representation technique that uses a two-dimensional array to store the connections between vertices. In this method, both rows and columns represent the vertices of the graph.

For a graph containing n vertices, the adjacency matrix has dimensions:

For a graph with (n) vertices, the adjacency matrix has dimensions:

n×n n\times n

The matrix entry is defined as:

A[i][j]={1amp;if an edge exists between i and j0amp;otherwise A[i][j]= \begin{cases} 1 & \text{if an edge exists between }i\text{ and }j\\ 0 & \text{otherwise} \end{cases}

2. Adjacency List

An Adjacency List is a graph representation technique that uses an array or collection of linked lists to store the connections between vertices. Each vertex maintains a separate list containing all the vertices directly connected to it.

In this representation, only the existing edges are stored, rather than maintaining a complete matrix of connections. Therefore, an adjacency list is memory-efficient and is especially useful for sparse graphs, where the number of edges is relatively small compared to the maximum possible number of edges.

Example of Adjacency List:

Consider a graph with three vertices A, B, and C, having edges A–B and B–C.

Its adjacency list representation is:

VertexAdjacent Vertices
AB
BA, C
CB

Here:

  • Vertex C is connected to vertex B.
  • Vertex A is connected to vertex B.
  • Vertex B is connected to vertices A and C.

Structure of an Adjacency List

In an adjacency list:

  • For a directed graph, the list contains only the vertices reachable through outgoing edges.
  • Each vertex in the graph has a corresponding list.
  • Each list contains all the adjacent vertices connected to that vertex.
  • For an undirected graph, if vertex A is connected to vertex B, both A’s and B’s lists contain the other vertex.

Graph Traversal

Graph traversal is the process of visiting the vertices of a graph systematically to explore its structure and connections. During traversal, each vertex is generally visited only once by maintaining a visited array to avoid repeated visits.

The two major graph traversal techniques are:

  • Depth First Search (DFS)
  • Breadth First Search (BFS)

Graph traversal is used to search for vertices, identify connected components, find paths between vertices, and explore networks such as social networks and computer networks.

Depth First Search (DFS)

Depth First Search (DFS) is a graph traversal algorithm that explores a graph by going as deep as possible along one path before backtracking to explore other paths.

It starts from a selected vertex, visits one of its unvisited adjacent vertices, and continues exploring deeper until no unvisited adjacent vertices are available. It then backtracks to the previous vertex and explores the remaining unvisited vertices.

DFS uses a Stack data structure to keep track of vertices. It can be implemented in two ways: using an explicit stack or using recursion, which internally uses the function call stack.

DFS uses:

  • Stack: Stores vertices whose adjacent vertices need to be explored.
  • Recursion: Provides an alternative way to implement DFS using function calls.
  • Visited Array: Keeps track of visited vertices to avoid visiting the same vertex repeatedly.

Working of DFS

  1. Select a Starting Vertex: Choose any vertex from the graph as the starting point for traversal.
  2. Mark as Visited: Mark the selected vertex as visited to avoid processing it again.
  3. Explore Adjacent Vertices: Select an unvisited vertex adjacent to the current vertex and move to it.
  4. Continue Deeper: Repeat the process by visiting unvisited adjacent vertices, exploring one path as deeply as possible.
  5. Backtrack: When the current vertex has no unvisited adjacent vertices, return to the previous vertex and check for other unvisited adjacent vertices.
  6. Repeat Traversal: Continue exploring and backtracking until all vertices reachable from the starting vertex have been visited.

DFS Algorithm (Recursive)

The recursive DFS algorithm uses function calls to explore the graph deeply before backtracking. It marks each vertex as visited and recursively calls DFS for every unvisited adjacent vertex.

DFS(G, v):
    mark v as visited
    print v

    for each adjacent vertex u of v:
        if u is not visited:
            DFS(G, u)
DFS

Step-by-Step Traversal of DFS

1. Start at Vertex 1: Begin the traversal from vertex 1 and mark it as visited.

2. Visit Vertex 2: Move to the unvisited adjacent vertex 2 and mark it as visited.

3. Visit Vertex 4: From vertex 2, move to vertex 4. Mark vertex 4 as visited.

4. Backtrack to Vertex 2: Vertex 4 has no unvisited adjacent vertices. Therefore, backtrack to vertex 2.

5. Visit Vertex 5: From vertex 2, visit the next unvisited adjacent vertex 5.

6. Backtrack to Vertex 1 and Visit Vertex 3: Since vertex 5 has no unvisited adjacent vertices, backtrack to vertex 2 and then vertex 1. From vertex 1, visit vertex 3.

7. Visit Vertex 6: From vertex 3, move to vertex 6 and mark it as visited.

8. Visit Vertex 7: After visiting vertex 6, backtrack to vertex 3 and visit the remaining unvisited adjacent vertex 7.

9. Complete Traversal: All vertices have been visited, so the DFS traversal is completed.

DFS Traversal Order

The vertices are visited in the following order:

1→2→4→5→3→6→7\boxed{1\rightarrow2\rightarrow4\rightarrow5\rightarrow3\rightarrow6\rightarrow7}

DFS Algorithm (Using Stack)

The iterative DFS algorithm uses an explicit Stack data structure instead of recursion to traverse a graph. It follows the Last In, First Out (LIFO) principle, meaning the vertex inserted last is processed first.

DFS_Stack(G, start):
    create empty stack S
    push start into S

    while S is not empty:
        v = pop(S)

        if v is not visited:
            mark v as visited
            print v

            for each unvisited neighbor u of v:
                push u into S

Note: The traversal order may vary depending on the order in which adjacent vertices are pushed onto the stack. This iterative implementation may produce a different traversal order from recursive DFS.

Breadth First Search (BFS)

Breadth First Search (BFS) is a graph traversal algorithm that explores a graph level by level. It starts from a selected vertex and visits all its adjacent vertices before moving to the next level. This process continues until all reachable vertices have been visited.

BFS uses a Queue data structure to keep track of vertices that need to be explored. It follows the First In, First Out (FIFO) principle, meaning the vertex inserted first is removed and processed first.

BFS is particularly useful for finding the shortest path between vertices in an unweighted graph.

It uses a Queue data structure.

Working of BFS

  1. Select a Starting Vertex: Choose any vertex from the graph as the starting point for traversal.
  2. Mark as Visited: Mark the starting vertex as visited to avoid visiting it again.
  3. Insert into Queue: Insert the starting vertex into the queue using the enqueue() operation.
  4. Remove from Queue: Remove the vertex at the front of the queue using the dequeue() operation.
  5. Explore Adjacent Vertices: Check all vertices directly connected to the removed vertex.
  6. Mark and Insert: Mark each unvisited adjacent vertex as visited and insert it into the queue.
  7. Repeat the Process: Continue removing vertices from the queue and exploring their unvisited adjacent vertices until the queue becomes empty.

BFS Algorithm

Breadth First Search uses a Queue data structure to traverse a graph level by level. It first visits the starting vertex, then processes all its unvisited adjacent vertices before moving to the next level.

BFS(G, start):
    create an empty queue Q

    mark start as visited
    enqueue(start)

    while Q is not empty:
        v = dequeue(Q)
        print v

        for each adjacent vertex u of v:
            if u is not visited:
                mark u as visited
                enqueue(u)
BFS

Step-by-Step Traversal of BFS

1. Start at Vertex 1: Begin the traversal from vertex 1 (Layer 0). Mark it as visited and insert it into the queue.

2. Visit Vertex 2: Remove vertex 1 from the queue and visit its first adjacent vertex, 2. Mark vertex 2 as visited and insert it into the queue.

3. Visit Vertex 3: Visit the next adjacent vertex of 1, which is vertex 3. Mark it as visited and insert it into the queue.

4. Visit Vertex 4: Remove vertex 2 from the queue and visit its first unvisited adjacent vertex, 4. Mark it as visited and insert it into the queue.

5. Visit Vertex 5: Visit the next unvisited adjacent vertex of 2, which is vertex 5. Mark it as visited and insert it into the queue.

6. Visit Vertex 6: Remove vertex 3 from the queue and visit its first unvisited adjacent vertex, 6. Mark it as visited and insert it into the queue.

7. Visit Vertex 7: Visit the next unvisited adjacent vertex of 3, which is vertex 7. Mark it as visited and insert it into the queue.

8. Complete Traversal: Continue removing vertices from the queue. Since all vertices have been visited and no more vertices remain to be explored, the queue becomes empty and BFS is completed.

BFS Traversal Order

The vertices are visited in the following order:

1→2→3→4→5→6→7\boxed{1\rightarrow2\rightarrow3\rightarrow4\rightarrow5\rightarrow6\rightarrow7}

DFS vs BFS

FeatureDFSBFS
Full FormDepth First SearchBreadth First Search
Data StructureStackQueue
StrategyDepth-wiseLevel-wise
ImplementationRecursion or stackQueue
Shortest pathNot guaranteedGuaranteed for unweighted graphs
MemoryOften less for deep graphsOften more for wide graphs
Time Complexity(O(V+E))(O(V+E))
ApplicationsCycle detection, topological sortShortest path, level traversal

Connected Components

A Connected Component is a maximal connected subgraph of an undirected graph. It is a group of vertices in which every vertex is reachable from every other vertex through one or more edges.

In simple terms, a connected component represents a separate group of interconnected vertices in a graph. If there is no path connecting two groups of vertices, they belong to different connected components.

A connected component has the following properties:

  • Connectivity: Every pair of vertices within the component must have at least one path connecting them.
  • Maximality: No additional vertex from the original graph can be included in the component without losing its connectivity property.
  • Independence: There must be no edge connecting a vertex in one component to a vertex in another component.
  • Complete Coverage: Every vertex in an undirected graph belongs to exactly one connected component.
Connected Components

How to Find Connected Components?

Connected components can be identified using graph traversal techniques such as Depth First Search (DFS) or Breadth First Search (BFS).

The process is as follows:

  1. Initialize all vertices as unvisited.
  2. Select an unvisited vertex from the graph.
  3. Perform DFS or BFS starting from that vertex.
  4. Mark all reachable vertices as visited. These vertices form one connected component.
  5. Select another unvisited vertex and repeat the process.
  6. Continue until all vertices have been visited.

Algorithm to Find Connected Components

ConnectedComponents(G):
    count = 0

    for each vertex v in G:
        if v is not visited:
            DFS(G, v)
            count = count + 1

    return count

Spanning Trees

A Spanning Tree is a subgraph of a connected, undirected graph that contains all the vertices of the original graph and connects them without forming any cycles.

It is obtained by selecting a subset of edges from the original graph while ensuring that every vertex remains reachable from every other vertex. A spanning tree uses the minimum number of edges required to maintain connectivity.

A connected graph may have more than one spanning tree because different combinations of edges can connect all the vertices without forming cycles. However, every spanning tree of the same graph has exactly V-1 edges.

Spanning trees are widely used in computer networks, communication systems, network design, and graph optimization problems.

Properties of Spanning Trees

  • Contains All Vertices: A spanning tree includes every vertex of the original graph. No vertex is left out.
  • Connected: Every vertex must be reachable from every other vertex through one or more edges.
  • No Cycles: A spanning tree does not contain any cycles. There is exactly one simple path between any two vertices.
  • Exactly V-1 Edges: If the original graph contains V vertices, its spanning tree always contains V-1 edges.
  • Minimal Connectivity: A spanning tree uses the minimum number of edges required to connect all vertices. Removing any edge makes the tree disconnected.
  • Multiple Spanning Trees: A connected graph can have multiple spanning trees, depending on which edges are selected.
Spanning Trees

Example of a Spanning Tree

Consider a connected undirected graph with five vertices: A, B, C, D, and E.

Suppose the graph contains the following edges:

A–B, A–C, B–C, B–D, C–D, C–E, and D–E.

One possible spanning tree can be formed by selecting the following edges:

A–B, A–C, B–D, and C–E.

In this spanning tree:

  • Number of vertices V = 5
  • Number of edges E = 4
  • Required number of edges = V-1=5-1=4

Applications of Spanning Trees

  • Computer Networks: Used to connect computers and network devices while avoiding unnecessary connections.
  • Communication Systems: Helps establish efficient connections between communication stations.
  • Transportation Networks: Used to connect cities through road or railway networks with fewer connections.
  • Electrical Networks: Helps design circuits that connect all required components without unnecessary loops.
  • Network Optimization: Provides the foundation for finding minimum-cost connections using Minimum Spanning Tree algorithms such as Prim’s and Kruskal’s algorithms.

Minimum Cost Spanning Trees (MST)

A Minimum Spanning Tree (MST) is a spanning tree of a connected, weighted, undirected graph that has the minimum possible total edge weight among all possible spanning trees of that graph.

A spanning tree connects all the vertices of a graph without forming any cycles. A Minimum Spanning Tree selects the edges in such a way that every vertex is connected with the lowest possible total cost.

In a weighted graph, each edge has a numerical value called a weight, which may represent distance, cost, time, or resource requirements. The MST aims to minimize the sum of these edge weights while ensuring that all vertices remain connected.

The total weight of a Minimum Spanning Tree is calculated by adding the weights of all the selected edges.

W(MST)=∑e∈Tw(e) W(MST)=\sum_{e\in T}w(e)

Properties of Minimum Spanning Tree

  • Includes All Vertices: Every vertex of the original graph must be included.
  • Connected: There must be a path between every pair of vertices.
  • No Cycles: The MST must not contain any cycles.
  • Minimum Total Weight: The sum of the weights of all selected edges must be as small as possible.
  • Exactly V-1 Edges: For a graph containing V vertices, an MST contains exactly V-1 edges.
  • Multiple MSTs: A graph may have more than one MST if different spanning trees have the same minimum total weight.

Prim’s Algorithm

Prim’s Algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, weighted, undirected graph. It starts from any selected vertex and gradually builds a spanning tree by adding one vertex at a time.

At each step, the algorithm selects the minimum-weight edge that connects a vertex already included in the spanning tree to a vertex that has not yet been included. This process continues until all vertices are added to the spanning tree.

Prim’s Algorithm ensures that all vertices are connected with the minimum possible total edge weight without forming any cycles.

Prim's Algorithm

Working of Prim’s Algorithm

  1. Start by selecting any vertex as the initial vertex of the spanning tree.
  2. Mark the selected vertex as visited.
  3. Find the minimum-weight edge connecting a visited vertex to an unvisited vertex.
  4. Select that edge and add the unvisited vertex to the spanning tree.
  5. Mark the newly added vertex as visited.
  6. Repeat the process by selecting the next minimum-weight edge connecting the visited and unvisited vertices.
  7. Continue until all vertices are included in the spanning tree and exactly V-1 edges have been selected.

Algorithm of Prim’s Algorithm

Prim(G):
    select a starting vertex
    MST = empty set

    mark starting vertex as visited

    while MST contains fewer than V-1 edges:
        select the minimum-weight edge (u, v)
        where u is visited and v is unvisited

        add (u, v) to MST
        mark v as visited

    return MST

Example of Prim’s Algorithm

Consider a weighted graph:

EdgeWeight
A – B2
A – C3
B – C1
B – D4
C – D5

Starting vertex: A

Step-by-Step Execution

StepSelected EdgeWeightMST Vertices
1A – B2A, B
2B – C1A, B, C
3B – D4A, B, C, D

Total Minimum Cost:

MST=2+1+4 MST=2+1+4

MST=7 \boxed{MST=7}

Kruskal’s Algorithm

Kruskal’s Algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, weighted, undirected graph. It constructs the spanning tree by selecting edges in increasing order of their weights, starting with the edge having the smallest weight.

Unlike Prim’s Algorithm, which starts from a vertex and gradually expands the spanning tree, Kruskal’s Algorithm focuses on selecting the smallest available edges from the entire graph.

At each step, the algorithm checks whether adding an edge creates a cycle. If the edge does not form a cycle, it is included in the Minimum Spanning Tree. Otherwise, that edge is skipped.

The process continues until all vertices are connected and exactly V-1 edges have been selected.

Kruskal's Algorithm

Working of Kruskal’s Algorithm

  1. Start with an empty Minimum Spanning Tree.
  2. Sort all the edges of the graph in increasing order of their weights.
  3. Select the edge with the smallest weight.
  4. Check whether adding the selected edge creates a cycle.
  5. If it does not form a cycle, add the edge to the spanning tree.
  6. If it forms a cycle, discard the edge and select the next smallest edge.
  7. Repeat the process until the spanning tree contains exactly V-1 edges.

Algorithm of Kruskal’s Algorithm

Kruskal(G):
    MST = empty set

    sort all edges by increasing weight

    for each edge (u, v) in sorted order:
        if adding (u, v) does not create a cycle:
            add (u, v) to MST

        if MST contains V-1 edges:
            break

    return MST

Cycle Detection in Kruskal’s Algorithm

Kruskal’s Algorithm uses a Disjoint Set Union (DSU) or Union-Find data structure to detect cycles while constructing a Minimum Spanning Tree.

Initially, each vertex is treated as a separate set. When an edge is selected, the algorithm checks whether its two endpoints belong to the same set or different sets.

The Disjoint Set Union data structure uses two important operations:

  • Find(x): Determines the set or representative to which vertex x belongs.
  • Union(x, y): Combines the two sets containing vertices x and y into a single set.

How Does Cycle Detection Work?

  • Select an edge connecting two vertices, u and v.
  • Perform Find(u) and Find(v) to identify their respective sets.
  • If both vertices belong to the same set, adding the edge would create a cycle. Therefore, discard the edge.
  • If they belong to different sets, adding the edge will not create a cycle. Include the edge in the Minimum Spanning Tree.
  • Perform Union(u, v) to combine their sets.
  • Repeat the process until V-1 edges have been selected.

Example of Cycle Detection

Using the same graph:

EdgeWeight
A – B2
A – C3
B – C1
B – D4
C – D5

Sorted Edges:

BC(1),AB(2),AC(3),BD(4),CD(5) BC(1),AB(2),AC(3),BD(4),CD(5)

Step-by-Step Execution

StepEdgeWeightDecision
1B – C1Select
2A – B2Select
3A – C3Reject (Cycle)
4B – D4Select

Total Cost:

MST=1+2+4 MST=1+2+4

MST=7 \boxed{MST=7}

Graph Algorithms

1. Transitive Closure

The Transitive Closure of a directed graph is a representation that shows whether a path exists between every pair of vertices in the graph.

In simple terms, it determines whether one vertex can reach another vertex directly or indirectly through a sequence of edges.

For example, consider a directed graph containing the following connections:

  • A → B
  • B → C

Although there is no direct edge from A to C, a path exists from A to C through vertex B. Therefore, the transitive closure indicates that A can reach C.

It is also called the reachability matrix.

The transitive closure matrix (T) is defined as:

T[i][j]={1amp;if a path exists from i to j0amp;otherwiseT[i][j]= \begin{cases} 1 & \text{if a path exists from }i\text{ to }j\\ 0 & \text{otherwise} \end{cases}

Properties of Transitive Closure

  • It represents the reachability relationship between all pairs of vertices.
  • It includes both direct and indirect connections.
  • It is generally represented using a Boolean adjacency matrix.
  • If a path exists between two vertices, the corresponding matrix entry is 1; otherwise, it is 0.
  • It is useful in dependency analysis, network connectivity, and database relationship analysis.

Applications of Transitive Closure

  • Reachability analysis
  • Network connectivity
  • Dependency analysis
  • Database relationship queries
  • Compiler dependency checking

2. Shortest Path

The shortest path is the path between two vertices in a graph that has the minimum total weight or cost. In a weighted graph, each edge has a numerical value called a weight, which may represent distance, time, or travel cost. The shortest path is found by adding the weights of all edges along each possible path and selecting the path with the smallest total value.

Example: Consider three vertices A, B, and C with the following edge weights:

  • A → B = 5
  • B → C = 3
  • A → C = 10

There are two possible paths from A to C:

  1. Direct path (A → C): Cost = 10
  2. Indirect path (A → B → C): Cost = 5 + 3 = 8

Therefore, the shortest path is A → B → C, with a minimum total cost of 8.

Types of Shortest Path Problems

Shortest path problems can be classified into the following types:

  1. Single-Source Shortest Path: Finds the shortest paths from one selected source vertex to all other vertices in the graph.
  2. Single-Pair Shortest Path: Finds the shortest path between a specific pair of vertices.
  3. All-Pairs Shortest Path: Finds the shortest paths between every pair of vertices in the graph.

Warshall’s Algorithm

Warshall’s Algorithm is a graph algorithm used to find the transitive closure of a directed graph. It determines whether a path exists between every pair of vertices, considering both direct and indirect connections.

It uses an adjacency matrix to represent the graph and follows a Dynamic Programming approach to calculate the reachability between vertices.

The algorithm works by considering each vertex as an intermediate vertex and checking whether it creates a new path between other pairs of vertices. If a path exists through an intermediate vertex, the corresponding entry in the matrix is updated to 1.

The main purpose of Warshall’s Algorithm is to determine whether one vertex can reach another vertex through a direct edge or through a sequence of intermediate vertices.

Principle of Warshall’s Algorithm

Warshall’s Algorithm checks whether a path from vertex (i) to vertex (j) can be formed through an intermediate vertex (k).The recurrence relation is:

R[i][j]=R[i][j]∨(R[i][k]∧R[k][j]) R[i][j]=R[i][j]\lor(R[i][k]\land R[k][j])

Algorithm of Warshall’s Algorithm

The algorithm follows these steps:

  1. Start with the adjacency matrix of the directed graph.
  2. Create a reachability matrix using the adjacency matrix.
  3. Consider each vertex as an intermediate vertex, one at a time.
  4. Check whether a path exists from vertex i to vertex j through the intermediate vertex k.
  5. If such a path exists, update the corresponding matrix entry to 1.
  6. Repeat the process for all vertices.
  7. The final matrix represents the transitive closure of the graph.

Dijkstra’s Algorithm

Dijkstra’s Algorithm is a greedy algorithm used to find the shortest paths from a selected source vertex to all other vertices in a weighted graph with non-negative edge weights.

It works by selecting the unvisited vertex with the smallest known distance from the source and updating the shortest distances of its adjacent vertices.

This process continues until the shortest distances to all reachable vertices have been determined.

Dijkstra’s Algorithm maintains a distance array to store the shortest known distance from the source vertex to every other vertex.

Important Terms Used in Dijkstra’s Algorithm

  • Source Vertex: The starting vertex from which shortest paths are calculated.
  • Distance Array: Stores the current shortest known distance from the source to each vertex.
  • Visited Array: Keeps track of vertices whose shortest distances have been finalized.
  • Relaxation: The process of checking whether a shorter path to an adjacent vertex can be found through the current vertex.
  • Infinity (∞): Represents an initially unknown or unreachable distance.

How Does Dijkstra’s Algorithm Work?

Dijkstra’s Algorithm follows a greedy approach by repeatedly selecting the unvisited vertex with the minimum tentative distance.

The working process is as follows:

  1. Select a source vertex from which the shortest paths need to be calculated.
  2. Initialize the distance of the source vertex to 0.
  3. Initialize the distances of all other vertices to infinity (∞).
  4. Mark all vertices as unvisited.
  5. Select the unvisited vertex having the smallest tentative distance.
  6. Mark the selected vertex as visited.
  7. Examine all its unvisited adjacent vertices and calculate their new distances through the selected vertex.
  8. If a newly calculated distance is smaller than the existing distance, update the distance array.
  9. Repeat the process until all reachable vertices have been visited or no reachable unvisited vertex remains.

Distance Update Formula

dist[v]=min⁡(dist[v],dist[u]+w(u,v)) \text{dist}[v]=\min(\text{dist}[v],\text{dist}[u]+w(u,v))

The distance to an adjacent vertex is updated using the following formula:

Where:

  • dist[u] = Shortest known distance from the source to the current vertex.
  • dist[v] = Current shortest known distance to the adjacent vertex.
  • w(u,v) = Weight of the edge connecting vertices u and v.

Dijkstra’s Algorithm

DIJKSTRA(G, source):

for each vertex v in G:
    dist[v] = INFINITY
    visited[v] = false

dist[source] = 0

repeat:
    u = unvisited vertex with minimum dist[u]

    if no such vertex exists:
        break

    visited[u] = true

    for each adjacent vertex v of u:

        if visited[v] == false:

            newDist = dist[u] + weight(u, v)

            if newDist < dist[v]:
                dist[v] = newDist

return dist

Important AKTU Examination Questions – Unit 4

  • Define graph and explain its different types.
  • Explain the terminology used in graph theory.
  • What is the difference between directed and undirected graphs?
  • Explain adjacency matrix and adjacency list.
  • Discuss the advantages and disadvantages of graph representations.
  • Explain connected components with an example.
  • Define spanning tree and discuss its properties.
  • What is a Minimum Spanning Tree?
  • Explain the greedy approach used in Prim’s and Kruskal’s algorithms.
  • Explain the difference between shortest path and minimum spanning tree.
  • What is transitive closure?Explain the limitations of Dijkstra’s Algorithm.

Explore More Resources of Data Structures

ResourceDescriptionLink
Data Structures Question BankPractice important questions, MCQs, and exam-oriented questions on Data Structures.Data Structure Previous Year Questions and Answers →
Data Structures Previous Year Question PapersPrepare using previous year university question papers for Data Structures.Data Structure Previous Year Question Papers →

Explore Other AKTU Data Structures Units

Continue your AKTU Data Structures preparation with complete unit-wise notes, explanations, diagrams, algorithms, and important questions.

Data Structures UnitStudy Notes
Unit 1 – Introduction to Data StructuresRead Unit 1 Notes→
Unit 2 – Stacks, Queues and RecursionRead Unit 2 Notes→
Unit 3 – Searching and SortingRead Unit 3 Notes→
Unit 5 – Trees and Binary TreesRead Unit 4 Notes→

Explore More Study Materials

Visit Quescol Home Page

Explore more AKTU B.Tech CSE notes, syllabus, and examination preparation resources on Quescol.