0% found this document useful (0 votes)
16 views154 pages

Unit 3 Dsa Graph 2022 1

Uploaded by

Gaurav Kathe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views154 pages

Unit 3 Dsa Graph 2022 1

Uploaded by

Gaurav Kathe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 154

SYLLABUS

SYLLABUS
Basic Concepts, Storage representation, Adjacency matrix,

adjacency list, adjacency multi list, inverse adjacency list.

Traversals - depth first and breadth first, Minimum

spanning Tree, Greedy algorithms for computing minimum

spanning tree- Prims and Kruskal Algorithms, Dikjtra's

Single source shortest path, All pairs shortest paths- Flyod-

Warshall Algorithm Topological ordering.


UNIT-
III
GRAPH
Introduction of Graph
A graph is a non-linear data structure, which
consists of vertices(or nodes) connected by
edges(or arcs) where edges may be directed or
undirected.
Introduction of 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.
Types of Graph :
1. Directed Graph
2. Undirected
Graph
3. Weighted
Graph
Undirecred 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 G(V, E) with 5 vertices (A, B, C, D, E) and
six edges ((A,B), (B,C), (C,E), (E,D), (D,B),
(D,A)) is shown in the
following figure.
Directed
Graph
A graph can be directed or undirected. However, in
an undirected graph, edges are not associated with
the directions with them. 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.
Wighted
A graph thatGraph
has a value associated with every
edge. The values corresponding to the edges are
called weights. A value in a weighted graph can
represent quantities such as cost, distance, and
time, depending on the graph. Weighted graphs
are typically used in modeling computer networks.
Terminologies of
Path
Graph
A path can be defined as the sequence of nodes
that are followed in order to reach some terminal
node V from the initial node U.

Closed Path
A path will be called as closed path if the initial
node is same as terminal node. A path will be
closed path if V0=VN.

Simple Path
If all the nodes of the graph are distinct with an
Terminologies of
Cycle
Graph
A cycle can be definedas the path which
has no repeated edges or vertices except the first
and last vertices.

Connected Graph
A connected graph is the one in which some path
exists between every two vertices (u, v) in V. There
are no isolated nodes in connected graph.
Terminologies of
Graph
Complete Graph
A complete graph is the one in which every node is
connected with all other nodes. A complete graph
contain n(n-1)/2 edges where n is the number of
nodes in the graph.
Terminologies of
Weighted Graph
Graph
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.
Terminologies of
Weighted Graph
Graph
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.

Digraph
A digraph is a directed graph in which each edge of
the graph is associated with some direction and the
traversing can be done only in the specified
Terminologies of
Loop
Graph
An edge that is associated with the similar end points
can be called as Loop.

Adjacent Nodes
If two nodes u and v are connected via an edge e, then
the nodes u and v are called as neighbours or adjacent
nodes.

Degree of the Node


A degree of a node is the number of
edges that are connected with that node. A
Terminologies of
Loop
Graph
An edge that is associated with the similar end points
can be called as Loop.

Adjacent Nodes
If two nodes u and v are connected via an edge e, then
the nodes u and v are called as neighbours or adjacent
nodes.

Degree of the Node


A degree of a node is the number of
edges that are connected with that node. A
Terminologies of
Graph
• Outgoing edges of
edges
a vertex are directed
that the vertex is

the origin.

• Incoming edges of a vertex are directed

edges that the vertex is the destination.

• The degree of a vertex in a graph is

the total number of edges incident to it.

• In a directed graph, the out-degree of a vertex is the

total number of outgoing edges


Terminologies of
Graph
Pendant Vertex

A vertex with degree one is called a


pendant vertex.

Isolated Vertex

A vertex with degree zero is called an


isolated vertex.
Terminologies of
Graph
Graph Abstract Data Type
1. create() :Graph

2. insert vertex(Graph, v) :Graph

3. delete vertex(Graph, v) :Graph

4. insert edge(Graph, u, v) :Graph

5. delete edge(Graph, u, v) :Graph

6. is empty(Graph) :Boolean;

7. end graph 20
Graph
Representation
Adjacency Matrix Representation of Graph
We can easily represent the graphs using the
following ways,

1. Adjacency matrix (sequential representation)

2. Adjacency list (linked representation)

3. Adjacency Multilist

4. Inverse Adjacency List


Graph
• By Representation
Graph representation, we simply mean the
technique which is to be used in order to store
some graph into the computer's memory.

• There are two ways to store Graph into the


computer's memory. In this part of this tutorial,
we discuss each one of them in detail.
Adjacency
1. Matrix
A sequential representation is an adjacency matrix.
2. It's used to show which nodes are next to one another.
I.e., is there any connection between nodes in a graph?
3. You create an MXM matrix G for this representation. If
an edge exists between vertex a and vertex b, the
corresponding element of G, gi,j = 1, otherwise gi,j = 0.
4. If there is a weighted graph, you can record the edge's
weight instead of 1s and 0s.
Adjacency
Matrix
Undirected Graph Representation :
Adjacency
Matrix
Directed Graph Representation :
Adjacency
Matrix
Weighted Undirected Graph Representation
Weight or cost is indicated at the graph's edge, a weighted
graph representing these values in the matrix
Adjacency
1. List is an adjacency list.
A linked representation

2. You keep a list of neighbors for each vertex in the graph

in this representation. It means that each vertex in the

graph has a list of its neighboring vertices.

3. You have an array of vertices indexed by the vertex

number, and the corresponding array member for each

vertex x points to a singly linked list of x's neighbors


Adjacency List
Weighted
Linked-List Undirected Graph Representation Using
Adjacency List
Weighted
Array Undirected Graph Representation Using an
Graph
Representation
1. Sequential Representation
• In sequential representation, we use adjacency
matrix to store the mapping represented by
vertices and edges. In adjacency matrix, the rows
and columns are represented by the graph
vertices. A graph having n vertices, will have a
dimension n x n.

• An entry Mij in the adjacency matrix


representation of an undirected graph G will be
Graph
Representation
An undirected graph and its
adjacency representation is shown in
matri
x
the following figure.

in the above figure, we can see the mapping among the vertices (A, B, C, D, E)
is represented by using the adjacency matrix which is also shown in the figure.
There exists different adjacency matrices for the directed and undirected graph.
In directed graph, an entry Aij will be 1 only when there is an edge directed from Vi to
Graph
Representation
An undirected graph and its
adjacency representation is shown in
matri
x
the following figure.
Graph
Representation
A directed graph and its adjacency matrix representation is shown in
the following figure.

Representation of weighted directed graph is different. Instead of filling the


entry by 1, the Non- zero entries of the adjacency matrix are represented by
the weight of respective edges.
Graph
Representation
The weighted directed graph along with the adjacency matrix
representation is shown in the following figure.
Graph
Representation
2. Linked Representation :

In the linked representation, an adjacency list is used to store the


Graph into the computer's memory.

Consider the undirected graph shown in the following figure and


check the adjacency list representation.
Graph
Representation
2. Linked Representation :
Graph
Representation
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 last node of the list. The sum
of the lengths of adjacency lists is equal to the twice of the
number of edges present in an undirected graph.

Consider the directed graph shown in the following figure and check
the adjacency list representation of the graph.
Graph
Representation

In a directed graph, the sum of lengths of all the adjacency lists is


equal to the number of edges present in the graph.

In the case of weighted directed graph, each node contains an extra


field that is called the weight of the node. The adjacency list
representation of a directed graph is shown in the following figure.
Graph
Representation
Graph Representation
Examples
Graph Representation
Examples
Graph Representation
Examples
 Multiclass are lists where nodes may be shared
among several other lists

43
 The node structure of such a list can be represented as
follows :

44
45
 Inverse adjacency lists is a set of lists that
contain one list for vertex

 Each list contains a node per vertex adjacent


to the vertex it represents

46
47
Graph
Representation
Degree of Vertex in
DegreeGraph
of Vertex in a Directed Graph

In a directed graph, each vertex has an indegree and an outdegree.

Indegree of a Graph
Indegree of vertex V is the number of edges which are coming into
the vertex V.
Notation − deg−(V).

Outdegree of a Graph
Outdegree of vertex V is the number of edges which are going out
from the vertex V.
Degree of Vertex in
Graph

In-degree : Out-degree
In-degree of a vertex is the number of Out-degree of a vertex is the number edges
edges coming to the vertex. which are coming out from the vertex.

In-degree of vertex 0 = 0 Out-degree of vertex 0 = 3


In-degree of vertex 1 = 1 Out-degree of vertex 1 = 2
In-degree of vertex 2 = 1 Out-degree of vertex 2 = 1
In-degree of vertex 3 = 3 Out-degree of vertex 3 = 1
In-degree of vertex 4 = 2 Out-degree of vertex 4 = 0
Degree of Vertex in
Graph

Vertex Indegree Outdegree


a 1 2
b 2 0
c 2 1
d 1 1
e 1 1
f 1 1
g 0 2
Graph Traversal
Algorithms
Traversing the graph means examining all the nodes and vertices of
the graph. There are two standard methods by using which, we can
traverse the graphs. Lets discuss each one of them in detail.

1. Breadth First Search

2. Depth First Search


BFS
1. Algorithms
Breadth-first search is a graph traversal algorithm that starts
traversing the graph from the root node and explores all the
neighboring nodes. Then, it selects the nearest node and
explores all the unvisited nodes. While using BFS for traversal,
any node in the graph can be considered as the root node.

2. BFS is the most commonly used approach. It is a recursive


algorithm to search all the vertices of a tree or graph data
structure. BFS puts every vertex of the graph into two categories
- visited and non-visited. It selects a single node in a graph and,
after that, visits all the nodes adjacent to the selected node
BFS
Algorithms
BFS
Algorithms
BFS
As in the example given above, BFS algorithm
Algorithms
traverses from A to B to E to F first then to C and
G lastly to D. It employs the following rules.

•Rule 1 − Visit the adjacent unvisited vertex.


Mark it as visited. Display it. Insert it in a queue.

•Rule 2 − If no adjacent vertex is found,


remove the first vertex from the queue.

•Rule 3 − Repeat Rule 1 and Rule 2 until


the queue is empty.
BFS
Step 1: SET STATUS = 1 (ready state)
for each node in G Algorithms
Step 2: Enqueue the starting node A
and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until
QUEUE is empty
Step 4: Dequeue a node N. Process it
and set its STATUS = 3
(processed state).
Step 5: Enqueue all the neighbours
of
N that are in the ready state
(whose STATUS = 1) and set
their STATUS = 2
(waiting state)
[END OF LOOP]
BFS Algorithms
Rule 1 − Visit the adjacent unvisited vertex. Mark it as
visited. Display it. Insert it in a queue.

Rule 2 − If no adjacent vertex is found, remove the first


vertex from the queue.

Rule 3 − Repeat Rule 1 and Rule 2 until the queue


is empty.
BFS
Algorithms
Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)

Step 3: Repeat Steps 4 and 5 until QUEUE is empty

Step 4: Dequeue a node N. Process it and set its


STATUS = 3 (processed state).

Step 5: Enqueue all the neighbours of N that are in the ready state
(whose STATUS = 1) and set

their STATUS = 2
(waiting state)
[END OF LOOP]
Example of BFS
Algorithms
Complexity of BFS
Algorithms
The time complexity of the BFS algorithm is

represented in the form of O(V + E), where V is the

number of nodes and E is the number of edges.

The space complexity of the algorithm is O(V).


Advantages and
• Disadvantages
Advantages :
of
BFS
1. A BFS will find the shortest path between the starting point and any other
reachable node.

2. A depth-first search will not necessarily find the shortest path.

• Disadvantages :
A BFS on a binary tree generally requires more memory than a DFS.
Application of BFS
1. Algorithms
BFS can be used to find the neighboring locations from a given source
location.

2. In a peer-to-peer network, BFS algorithm can be used as a traversal


method to find all the neighboring nodes. Most torrent clients, such as
BitTorrent, uTorrent, etc. employ this process to find "seeds" and
"peers" in the network.

3. BFS is used to determine the shortest path and minimum spanning tree.

4. BFSis also used in Cheney's technique to duplicate the


garbage collection.

5. It can be used in ford-Fulkerson method to compute the maximum


Application of BFS
1.Algorithms
To build index by search index

2. For GPS navigation

3. Path finding algorithms

4. Cycle detection in an undirected graph

5. In minimum spanning tree


Application BFS
of Algorithms
Depth First Search
(DFS)
Depth first search (DFS) algorithm starts with the initial node of the graph
G, and then goes to deeper and deeper until we find the goal node or
the node which has no children. The algorithm, then backtracks from the
dead end towards the most recent node that is yet to be completely
unexplored.

The data structure which is being used in DFS is stack. The process
is similar to BFS algorithm. In DFS, the edges that leads to an unvisited
node are called discovery edges while the edges that leads to an already
visited node are called block edges.
DFS
Depth First Search (DFS) algorithm traverses a
Algorithms
graph in a depthward motion and uses a stack to
remember to get the next vertex to start a search,
when a dead end occurs in any iteration.
•As in the example given above, DFS algorithm
traverses from A to B to C to D first then to E,
then to F and lastly to G. It employs the following
rules.
•Rule 1 − Visit the adjacent unvisited vertex.
Mark it as visited. Display it. Push it in a stack.

•Rule 2 − If no adjacent vertex is found, pop up


a vertex from the stack. (It will pop up all the
vertices from the stack, which do not have
adjacent vertices.)
•Rule 3 − Repeat Rule 1 and Rule 2 until the stack
is empty
DFS
Algorithms

Traversing the above graph in BFS fashion would result from A -> B -> E -
> F -> C -> G -> D. The algorithm starts from node A and traverses all its
child nodes. As soon as it encounters B, it seems that it has further child
nodes. So, the child nodes of B are traversed before proceeding to the next
child node of A
DFS
Step 1: SET STATUS = 1 (ready state) for each node in G
Algorithms
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting
state)

Step 3: Repeat Steps 4 and 5 until STACK is empty

Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)

Step 5: Push on the stack all the neighbours of N that are


in the ready state (whose STATUS = 1) and set their

STATUS = 2 (waiting state)

[END OF LOOP]

Step 6: EXIT
DFS Algorithms
Depth first search (DFS) algorithm starts with the initial node of the
graph G, and then goes to deeper and deeper until we find the goal
node or the node which has no children. The algorithm, then
backtracks from the dead end towards the most recent node that is
yet to be completely unexplored.

The data structure which is being used in DFS is stack. The process
is similar to BFS algorithm. In DFS, the edges that leads to an
unvisited node are called discovery edges while the edges that leads
to an already visited node are called block edges.
DFS Algorithms
DFS is an algorithm for finding or traversing graphs or trees
in depth-ward direction. The execution of the algorithm
begins at the root node and explores each branch before
backtracking. It uses a stack data structure to remember, to
get the subsequent vertex, and to start a search, whenever a
dead-end appears in any iteration.

The full form of DFS is Depth-first search.


DFS Algorithms
DFS Algorithms
Step 1: SET STATUS = 1 (ready state) for each node in G

Step 2: Push the starting node A on the stack and set its STATUS = 2
(waiting state)

Step 3: Repeat Steps 4 and 5 until STACK is empty

Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed
state)
Step 5: Push on the stack all the neighbours of N that are in the ready
state (whose STATUS = 1) and set their
STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
DFS Algorithms Example

The printing sequence of the graph will be :


H→A→D→F→B→C→G→E
Complexity of DFS Algorithms
Complexity of Depth First Search

The time complexity of the DFS algorithm is

represented in the form of O(V + E), where V is the

number of nodes and E is the number of edges.

The space complexity of the algorithm is O(V).


Example of DFS Algorithms
Advantages and Disadvantages of
• Advantages :
DFS
1. Depth-first search on a binary tree generally requires less memory
than breadth-first.

2. Depth-first search can be easily implemented with recursion..

• Disadvantages :
A DFS doesn't necessarily find the shortest path to a node, while
breadth- first search does.
Application of DFS Algorithms
1. For finding the path

2. To test if the graph is bipartite

3. For finding the strongly connected components of a

graph

4. For detecting cycles in a graph


BFS Vs DFS
sn BFS DFS
BFS finds the shortest path to DFS goes to the bottom of a
1 the destination. subtree, then backtracks.

The full form of BFS is The full form of DFS is Depth


2 Breadth- First Search. First Search.

It uses a queue to keep track of It uses a stack to keep track of


3 the next location to visit. the next location to visit.

BFS traverses according to tree DFS traverses according to tree


4 level. depth.

5 It is implemented using FIFO list. It is implemented using LIFO list.


It requires more memory as It requires less memory as
6 compare to DFS. compare to BFS.
BFS Vs DFS
sn BFS DFS
There is no need of There is a need of backtracking
7
backtracking in BFS. in DFS.

You can never be trapped into You can be trapped into infinite
8
finite loops. loops.

If you do not find any goal, you


If you do not find any goal, the
may need to expand many
9 leaf node backtracking may
nodes before the solution is
occur.
found.
Applications of
1. Graph
In Computer science graphs are used to represent the flow of
computation.

2. Google maps uses graphs for building transportation systems.

3. In Facebook, users are considered to be the vertices and if they


are friends then there is an edge running between them.

4. Graphs are used to define the flow of computation.

5. Graphs are used to represent networks of communication.

6. Graphs are used to represent data organization.

7. Graph theory is used to find shortest path in road or a network.


Tree Vs
Graph
Spanning Tree of Graph
A spanning tree is a subset of Graph G, which has all the vertices
covered with minimum possible number of edges. Hence, a
spanning tree does not have cycles and it cannot be disconnected..
MinimumSpanning
Tree
Spanning Tree of
• Graph
Spanning Tree Applications

1. Computer Network Routing Protocol

2. Cluster Analysis

3. Civil Network Planning

• Minimum Spanning tree Applications

1. To find paths in the map

2. To design networks like telecommunication networks,


water supply networks, and electrical grids.
GREEDY
STRATEGIES
Greedy algorithm :
An algorithm is designed to achieve optimum solution for a given
problem. In greedy algorithm approach, decisions are made from the
given solution domain. As being greedy, the closest solution that seems
to provide an optimum solution is chosen.

Example of greedy strategy :


1. Travelling Salesman Problem
2. Prim's Minimal Spanning Tree Algorithm
3. Kruskal's Minimal Spanning Tree Algorithm
4. Dijkstra's Minimal Spanning Tree Algorithm
5. Knapsack Problem
6. Job Scheduling Problem
GREEDY
STRATEGIES
1. Minimum Spanning tree (Prims or Kruskal’s algorithms)
The cost of the spanning tree is the sum of the weights of all the edges
in the tree. There can be many spanning trees. Minimum spanning tree is
the spanning tree where the cost is minimum among all the spanning
trees. There also can be many minimum spanning trees.
GREEDY
STRATEGIES
1. Kruskal’s algorithms :

Kruskal’s Algorithm builds the spanning tree by adding edges one by


one into a growing spanning tree. Kruskal's algorithm follows greedy
approach as in each iteration it finds an edge which has least weight and
add it to the growing spanning tree.

Algorithm Steps :

1. Sort the graph edges with respect to their weights.

2. Start adding edges to the MST from the edge with the smallest weight
until the edge of the largest weight.

3. Only add edges which doesn't form a cycle , edges which connect
only disconnected components.
GREEDY
STRATEGIES
1. Kruskal’s algorithms :

Kruskal's algorithm is a minimum spanning tree algorithm
that takes a graph as input and finds the subset of the edges of
that graph which

• form a tree that includes every vertex

• has the minimum sum of weights among all the trees that can
be formed from the graph
• Kruskal's Algorithm Complexity
• The time complexity Of Kruskal's Algorithm is: O(E log E).
GREEDY
STRATEGIES
1. Kruskal’s algorithms :
The steps for implementing Kruskal's algorithm are
as follows:

1. Sort all the edges from low weight to high

2. Take the edge with the lowest weight and add it to the
spanning tree. If adding the edge created a cycle, then
reject this edge.

3. Keep adding edges until we reach all vertices.


GREEDY
STRATEGIES
2. Kruskal’s algorithms : Example

.
GREEDY
STRATEGIES
2. Kruskal’s algorithms : Example

.
1
GREEDY
STRATEGIES
2. Kruskal’s algorithms : Example

.
GREEDY
STRATEGIES
2. Kruskal Algorithms : Example
GREEDY
STRATEGIES
1. Kruskal Algorithms : Example
GREEDY
STRATEGIES
1. Kruskal Algorithms :

Kruskal's Algorithm Applications

1. In order to layout electrical wiring

2. In computer network (LAN connection)


GREEDY
STRATEGIES
1. Kruskal Algorithms :
GREEDY
STRATEGIES
1. Kruskal Algorithms :
GREEDY
STRATEGIES
2. Prims algorithm: Prim’s Algorithm also use Greedy approach to find
the minimum spanning tree. In Prim’s Algorithm we grow the spanning
tree from a starting position. Unlike an edge in Kruskal's, we
add vertex to the growing spanning tree in Prim's.

Algorithm Steps:

1. Initialize the minimum spanning tree with a vertex chosen at random.

2.Find all the edges that connect the tree to new vertices, find the
minimum and add it to the tree.

3. Keep repeating step 2 until we get a minimum spanning tree.

Prim's Algorithm Complexity

The time complexity of Prim's algorithm is O(E log V).


GREEDY
STRATEGIES
2. Prims algorithm: Example
GREEDY
STRATEGIES
1. Prims’ algorithms : Example

.
1
GREEDY
STRATEGIES
2. Prims algorithm: Example
GREEDY
STRATEGIES
2. Prims algorithm: Example
GREEDY
STRATEGIES
2. Prims algorithm: Example
GREEDY
STRATEGIES
2. Prims algorithm: Example
GREEDY
STRATEGIES
2. Prims algorithm: Example

Kruska's algorithm.
GREEDY
STRATEGIES
2. Prims algorithm:

Prim's Algorithm Application


1. Laying cables of electrical wiring
2. In network designed
3. To make protocols in network cycles
Advantages of
Disadvantages of
Advantages :
Greedy approach
• The algorithm is easier to describe.

• This algorithm can perform better than other algorithms


(but, not in all cases).

Disadvantages :
• The greedy doesn't always produce the optimal
algorithm solution.
Applications of Greedy
Algorithms
• It is used in finding the shortest path.

• It is used to find the minimum spanning tree using


the prim's algorithm or the Kruskal's algorithm.

• It is used in a job sequencing with a deadline.

• This algorithm is also used to solve the


fractional knapsack problem.
Prim’s Vs Kruskal
Algorithms
Single
Source
Shorst
Dijkstra’s
• Algorithms
Dijkstra's algorithm allows us to find the shortest path
between any two vertices of a graph.

• It differs from the minimum spanning tree because the


shortest distance between two vertices might not include
all the vertices of the graph.
How Dijkstra’s Algorithms
works?
• Dijkstra's Algorithm works on the basis that any subpath
B -> D of the shortest path A -> D between vertices A
and D is also the shortest path between vertices B and D.
How Dijkstra’s Algorithms
works?
• Djikstra used this property in the opposite direction i.e
we overestimate the distance of each vertex from the
starting vertex. Then we visit each node and its
neighbors to find the shortest subpath to those
neighbors.

• The algorithm uses a greedy approach in the sense that


we find the next best solution hoping that the end result
is the best solution for the whole problem.
Algorithms of Dijkstra’s
Algorithms
Algorithms of Dijkstra’s
function dijkstra(G, S)
Algorithms
for each vertex V in G
distance[V] <- infinite
previous[V] <- NULL
If V != S, add V to Priority Queue Q
distance[S] <- 0

while Q IS NOT EMPTY


U <- Extract MIN from Q
for each unvisited neighbour V of
U
tempDistance <- distance[U] + edge_weight(U,
V) if tempDistance < distance[V]
distance[V] <-
tempDistance previous[V]
Exampleof Dijkstra’s
•Algorithms
Example of Dijkstra's algorithm
It is easier to start with an example and then think about the
algorithm.

1. Start with a weighted


Exampleof Dijkstra’s
•Algorithms
Example of Dijkstra's algorithm

Choose a starting vertex and assign infinity path


values to all other devices
Exampleof Dijkstra’s
•Algorithms
Example of Dijkstra's algorithm

Go to each vertex and update its path


length
Exampleof Dijkstra’s
Algorithms

If the path length of the adjacent vertex is lesser


than new path length, don't update it
Exampleof Dijkstra’s
Algorithms

Avoid updating path lengths of already visited vertices


Exampleof Dijkstra’s
Algorithms

After each iteration, we pick the unvisited vertex


with the least path length. So we choose 5 before
7
Exampleof Dijkstra’s
Algorithms

Notice how the rightmost vertex has its path


length updated twice
Exampleof Dijkstra’s
Algorithms

Repeat until all the vertices have been


visited
Exampleof Dijkstra’s
Algorithms

https://www.freecodecamp.org/news/dijkstras-shortest-path-algorithm-
visual-introduction/
Exampleof Dijkstra’s
Algorithms

ANSWERs : https://www.freecodecamp.org/news/dijkstras-shortest-path-
algorithm-visual-introduction/
Exampleof Dijkstra’s
Algorithms
Time Complexity Dijkstra’s
Algorithms
• Time Complexity: O(E Log V)

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


of vertices.

• Space Complexity: O(V)


Applications of Dijkstra’s
•Algorithms
To find the shortest path

• In social networking applications

• In a telephone network

• To find the locations in the map


Example of Dijkstra’s
Algorithms
Example of Dijkstra’s
Algorithms
All Pair

Shorst
Floyd-Warshall
• Algorithms
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.
Floyd-Warshall
n = no Algorithms
of vertices

A = matrix of dimension n*n

for k = 1 to n

for i = 1 to n

for j = 1 to n
Ak[i, j] =
min (Ak-
1[i, j],
Ak-1[i, k]
+ Ak-1[k,
Example of Floyd-Warshall
Algorithms

Initial graph
Example : https://www.programiz.com/dsa/floyd-warshall-algorithm
Example of Floyd-Warshall
Algorithms

Fill each cell with the distance between ith and jth vertex
Example of Floyd-Warshall
Algorithms

Calculate the distance from the source vertex to


destination vertex through this vertex k
Example of Floyd-Warshall
Algorithms

Calculate the distance from the source vertex to


destination vertex through this vertex 2
Example of Floyd-Warshall
Algorithms

Calculate the distance from the source vertex to


destination vertex through this vertex 3
Example of Floyd-Warshall
Algorithms

Calculate the distance from the source vertex to


destination vertex through this vertex 4
A4 gives the shortest path between each pair of
vertices.
Floyd-Warshall
• Algorithms
Advantages :

1. It is extremely simple.

2. It is easy to implement.
Floyd-Warshall
• Algorithms
Time Complexity
There are three loops. Each loop has constant complexities.
So, the time complexity of the Floyd-Warshall algorithm is
3
O(n ).

• Space Complexity
The space complexity of the Floyd-Warshall algorithm
2
is O(n ).
Applications of Floyd-
Warshall
Algorithms
1. To find the shortest path is a directed graph

2. To find the transitive closure of


directed graphs

3. To find the Inversion of real matrices

4. For testing whether an undirected


graph is bipartite
Example of Floyd-Warshall
Algorithms
Example of Floyd-Warshall
Algorithms
Topologi
cal
Ordering
Topological
• Sort/Ordering
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.
Topological
Sort/Ordering
Find the number of different topological orderings possible for the
given graph-

Step-01:

Write in-degree of each vertex-


Topological
Step-02:Sort/Ordering
• Vertex-A has the least in-degree.
• So, remove vertex-A and its associated edges.
• Now, update the in-degree of other vertices.
Topological
Step-03:Sort/Ordering
• Vertex-B has the least in-degree.
• So, remove vertex-B and its associated edges.
• Now, update the in-degree of other vertices.
Topological
Step-04:Sort/Ordering
• There are two vertices with the least in-degree. So, following 2
cases are possible-
In case-01,
1. Remove vertex-C and its associated edges.
2. Then, update the in-degree of other vertices.

In case-02,
3. Remove vertex-D and its associated edges.
4. Then, update the in-degree of other vertices.
Topological
Step-04:Sort/Ordering
Topological
Sort/Ordering
Conclusion-

For the given graph, following 2 different topological


orderings are possible-

ABCDE
ABDC
E
Topological
Sort/Ordering

Folowing are the 4 different Topological order :


123456
123465
132456
132465
https://www.gatevidyalay.com/topological-so
Applications of
Topological
• Sort/Ordering
Few important applications of topological sort are-

1. Scheduling jobs from the given dependencies among jobs

2. Instruction Scheduling

3. Determining the order of compilation tasks to perform in


makefiles

4. Data Serialization

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy