0% found this document useful (0 votes)
21 views82 pages

DS Unit 4

The document provides an overview of graphs as data structures consisting of vertices and edges, detailing various types of graphs, such as directed, undirected, weighted, cyclic, and acyclic graphs. It discusses graph representation methods, including adjacency matrices and lists, as well as traversal algorithms like Depth First Search (DFS) and Breadth First Search (BFS). Additionally, it covers minimum spanning tree algorithms, specifically Prim's and Kruskal's algorithms, highlighting their applications and steps for implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views82 pages

DS Unit 4

The document provides an overview of graphs as data structures consisting of vertices and edges, detailing various types of graphs, such as directed, undirected, weighted, cyclic, and acyclic graphs. It discusses graph representation methods, including adjacency matrices and lists, as well as traversal algorithms like Depth First Search (DFS) and Breadth First Search (BFS). Additionally, it covers minimum spanning tree algorithms, specifically Prim's and Kruskal's algorithms, highlighting their applications and steps for implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

UNIT-IV

Graphs
● A Graph is a data structure that consists of a set of nodes
(vertices) and a set of edges that relate the nodes to each
other

● The set of edges describes relationships among the vertices .

● A graph G is defined as follows:

G=(V,E)
V(G): a finite set of vertices
E(G): a set of edges (pairs of vertices)
Examples of Graphs
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.
Examples of Graphs
Social Networks:
• Each person is a vertex, and relationships (like friendships) are
the edges. Algorithms can suggest potential friends.

Maps and Navigation:


•Locations, like a town or bus stops, are stored as vertices, and
roads are stored as edges. Algorithms can find the shortest
route between two locations when stored as a Graph.

Internet:
•Can be represented as a Graph, with web pages as vertices and
hyperlinks as edges.
TYPES OF GRAPHS
Directed vs. Undirected Graphs
Undirected Graph
● has no orientation (no arrow head)
● A Undirected Graph is when the edges between the vertex pairs
have no direction.
u v
Directed Graph
● has an orientation (has an arrow head)

● A directed Graph, also known as a digraph, is when the edges


between the vertex pairs have a direction.
u v
directed edge
Directed vs. Undirected Graphs
Weighted graph:
A weighted Graph is a Graph where the edges have values. The
weight value of an edge can represent things like distance, capacity,
time, or probability.
Strongly Connected Graph
A directed graph is strongly connected if there is a path between any
two pair of vertices. Simply, if it is possible to reach any vertex
starting from any other vertex in the graph that is called a Strongly
Connected Graph.
Trivial Graph
A graph having only one vertex in
it is called as a trivial graph.
It is the smallest possible graph.

Complete Graph
A graph in which a
every vertex is
connected to every
other vertex by an
edge.
Cyclic Graph
A graph containing at least one
cycle in it is called as a cyclic
graph.

Acyclic Graph
A graph not containing
any cycle in it is called
as an acyclic graph
Graph terminology
● Adjacent nodes: two nodes are adjacent if they are
connected by an edge

5 is adjacent to 7
7 is adjacent from 5

● A cycle is a simple path with the same start and


end vertex.
Degree of a Node:
Degree : The Degree of a node
is the number of arcs incident
to it.

Types :-
1. Indegree :- The number of
arcs entering the node is called
indegree of that node.

2. Outdegree :- The number of


arcs exiting from the node is
called outdegree of that node.
Continued…

● The degree of vertex i is the no. of edges incident on


vertex i.

e.g., degree(2) = 2, degree(5) = 3, degree(3) = 1


Continued…
● Loops: edges that connect a vertex to itself
● Paths: sequences of vertices p0, p1, … pm such
that each adjacent pair of vertices are connected
by an edge
● Multiple Edges: two nodes may be connected by
>1 edge
● Simple Graphs: have no loops and no multiple
edges
Graph Representation
● There are two different ways of representing a graph
in data structure:
● Adjacency matrix representation
● Adjacency lists representation
Adjacency Matrix
● An adjacency matrix is a 2D array in which each cell
represents the presence or absence of an edge between
two vertices.
● If an edge exists from vertex i to vertex j, the cell (i, j)
contains a non-zero value (often 1); otherwise, it
includes 0.
● In adjacency matrix, a value of 1 indicates the presence
of an edge between the corresponding vertices, while 0
indicates no edge.
Adjacency Matrix For undirected graph
Adjacency Matrix For directed graph
Adjacency Matrix For Weighted graph
Adjacency Matrix

1 2

3 4

5
Adjacency Lists Representation
● Adjacency list is a linked representation.
● In this representation, for each vertex in the graph,
we maintain the list of its neighbors.
● It means, every vertex of the graph contains list of
its adjacent vertices.
● Each row in adjacency matrix is represented as an
adjacency list.
Graphs: Adjacency List

24
Topological Sort
• Topological Sort is a linear ordering of the
vertices in such a way that if there is an edge
in the DAG going from vertex ‘u’ to vertex ‘v’,
then ‘u’ comes before ‘v’ in the ordering.
• 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.

25
Topological Sort Example

26
Topological Sort Example
Step-01:
• Write in-degree of each vertex-

27
Topological Sort Example
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.

28
Topological Sort Example
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.

29
Topological Sort Example
Step-04:
• There are two vertices with the least in-
degree. So, following 2 cases are possible-
In case-01, In case-02,
•Remove •Remove
vertex-C and its vertex-D and
associated its associated
edges. edges.
•Then, update •Then, update
the in-degree of the in-degree
other vertices. of other
vertices.

30
Topological Sort Example
Step-05:
• There are two vertices with the least in-
degree. So, following 2 cases are possible-
In case-01, In case-02,
•Remove vertex-D since it has the •Remove vertex-C since it has
least in-degree. the least in-degree.
•Then, remove the remaining vertex- •Then, remove the remaining
E. vertex-E.

31
Topological Sort Example

• For the given graph, following 2 different


topological orderings are possible-
• ABCDE
• ABDCE

32
33
Topological Sort

Advantages of Topological Sort:


• provides a linear ordering of tasks which helps in
scheduling tasks or events based on
dependencies.
• Detects cycles in a directed graph.
Disadvantages of Topological Sort:
• Only applicable to directed acyclic graphs (DAGs),
not suitable for cyclic graphs.

34
Graphs Traversal

 Graph Traversal is a process to visit the vertices and


edges of the directed graph in a systematic manner.
 To traverse a Graph means to start in one vertex, and
go along the edges to visit other vertices until all
vertices, or as many as possible, have been visited.
 The two most common ways a Graph can be traversed
are:
• Depth First Search (DFS)
• Breadth First Search (BFS)

35
Graphs Traversal-Breadth First Search(BFS)
 It is also known as level order traversal.
 The Queue data structure that follows first in first out is used for
Breadth First Search traversal.
 It begins with a node, then first traverses all its adjacent vertices.
 Once all adjacent vertices are visited, then their adjacent are
traversed.
Algorithmic Steps
Step 1 - Define a Queue of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that
vertex and insert it into the Queue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is
at front of the Queue and insert them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex
which is at front of the Queue then delete that vertex.
Step 5 - Repeat steps 3 and 4 until queue becomes empty.
Step 6 - When queue becomes empty, then produce final spanning
tree by removing unused edges from the graph 36
Graphs Traversal-Breadth First Search

37
Graphs Traversal-Breadth First Search

38
Graphs Traversal-Breadth First Search

39
Graphs Traversal-Breadth First Search

40
Graphs Traversal-Breadth First Search

BFS: A D E B C F G
41
Graphs Traversal-Breadth First Search

Routine
Void BFS (vertex v)
{
Visited[v]=TRUE;
For each w adjacent to v;
if (visited[w]==0)
BFS (G,V);
}

42
Graphs Traversal-Depth First Search
 DFS is also called Edge Based Traversal because it explores the nodes
along the edge or path.
 It uses the Stack data structure which follows Last in First out.
 The depth-first search (DFS) algorithm starts with the initial node of
graph G and goes deeper until we find the goal node or the node with
no children.
Algorithmic Steps
Step 1 - Define a Stack of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that vertex
and push it on to the Stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex
which is at the top of stack and push it on to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the
vertex which is at the top of the stack.
Step 5 - When there is no new vertex to visit then use back tracking and
pop one vertex from the stack.
Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7 - When stack becomes Empty, then produce final spanning tree by
removing unused edges from the graph 43
Graphs Traversal-Depth First Search

44
Graphs Traversal-Depth First Search

45
Graphs Traversal-Depth First Search

46
Graphs Traversal-Depth First Search

47
Graphs Traversal-Depth First Search

48
Graphs Traversal-Depth First Search

49
Graphs Traversal-Depth First Search

DFS: A B C E D F G 50
Graphs Traversal-Depth First Search

DFS: A B C E D F G

51
Graphs Traversal
Routine
Void DFS(vertex v)
{
Visited[v]=TRUE;
For each w adjacent to v;
if (!visited[w])
DFS (w);
}
52
Minimum spanning tree
Spanning Trees
A subgraph T of a undirected graph G=(V, E) is a
spanning tree of G if it is a tree and contains every
vertex of G

53
Minimum spanning tree
A Minimum Spanning Tree in an undirected connected
weighted graph can be defined as the spanning tree
(among all spanning trees) in which the sum of the
weights of the edge is minimum.

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

55
Prim's Algorithm
• The steps for implementing Prim's algorithm are as
follows:
 Initialize the minimum spanning tree with a
vertex chosen at random.
 Finding the edge with the lowest weight that
connects the tree to a vertex not yet in the tree
 Adding the edge to the MST if it doesn't create a
closed cycle
 Repeating steps 2 and 3 until all vertices are in
the MST

56
Example of Prim's Algorithm

Step 1 - First, we have to choose a vertex from the above


graph. Let's choose S.

57
Example of Prim's Algorithm
Step 2
• Since B is the last visited, check for the least cost
edge that is connected to the vertex B.
B→A=9
B → C = 16
B → E = 14
• Least cost edge from B is A,
so B → A is the edge added to
the spanning tree.

58
Example of Prim's Algorithm
Step 3
• Since A is the last visited, check for the least cost edge that is
connected to the vertex A
A → C = 22
A→B=9
A → E = 11
• But A → B is already in the
spanning tree, check for the
next least cost edge. Hence,
A → E is added to the spanning
tree.

59
Example of Prim's Algorithm
Step 4
• Since E is the last visited, check for the least cost edge that is
connected to the vertex E.
E → C = 18
E→D=3
Therefore, E → D is added
to the spanning tree.

60
Example of Prim's Algorithm
Step 5
• Since D is the last visited, check for the least cost edge that is
connected to the vertex D.
• D → C = 15
• E→D=3
• Therefore, D → C is
added to the spanning
tree.

The minimum spanning tree is obtained with the


minimum cost = 46
61
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 which
we can traverse every vertex of the graph.
• It follows the greedy approach that finds an optimum solution at every
stage.
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 –
1. First, sort all the edges from low weight to high.
2. 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.
3. Continue to add the edges until we reach all vertices, and a minimum
spanning tree is created.
62
Kruskal’s Algorithm
Applications of Kruskal's algorithm:
• Kruskal's algorithm can be used to layout electrical wiring
among cities.
• It can be used to lay down LAN connections.

63
Example of Kruskal’s Algorithm
Construct a minimum spanning tree using
kruskal’s algorithm for the graph given below −

The graph contains 9 vertices and 14 edges. So, the


minimum spanning tree formed will be having (9 – 1) = 8
edges. 64
Example of Kruskal’s Algorithm

65
Example of Kruskal’s Algorithm

Step 1: Pick edge 7-6. No cycle is formed,


include it.

66
Example of Kruskal’s Algorithm
Step 2: Pick edge 8-2. No cycle is formed, include it.

67
Example of Kruskal’s Algorithm
Step 3: Pick edge 6-5. No cycle is formed, include it.

68
Example of Kruskal’s Algorithm
Step 4: Pick edge 0-1. No cycle is formed, include it.

69
Example of Kruskal’s Algorithm
Step 5: Pick edge 2-5. No cycle is formed, include it.

70
Example of Kruskal’s Algorithm
Step 6: Pick edge 8-6. Since including this edge results in the cycle,
discard it. Pick edge 2-3: No cycle is formed, include it.

71
Example of Kruskal’s Algorithm
Step 7: Pick edge 7-8. Since including this edge results in the cycle,
discard it. Pick edge 0-7. No cycle is formed, include it.

72
Example of Kruskal’s Algorithm
Step 8: Pick edge 1-2. Since including this edge results in the cycle,
discard it. Pick edge 3-4. No cycle is formed, include it.

The minimum spanning tree is obtained with the


minimum cost = 37 73
Shortest path problem
• The shortest path algorithms are the ones that
focuses on calculating the minimum travelling
cost from source node to destination node of a
graph in optimal time and space complexities.
• The shortest path problem involves finding the
shortest path between two vertices (or nodes) in
a graph.
• Algorithms such as the Floyd-Warshall algorithm
and different variations of Dijkstra's algorithm are
used to find solutions to the shortest path
problem.
Dijkstra's algorithm
• Dijkstra’s algorithm is designed to find the
shortest path in the graph from one vertex to
other remaining vertices in the graph.
• It can be performed on both directed and
undirected graphs.
• Since the shortest path can be calculated from
single source vertex to all the other vertices in
the graph, Dijkstra’s algorithm is also
called single-source shortest path algorithm.
Dijkstra's algorithm
Dijkstra's algorithm
Dijkstra's algorithm
Dijkstra's algorithm
Dijkstra pseudocode
Dijkstra(v1, v2):
for each vertex v: // Initialization
v's distance := infinity.
v's previous := none.
v1's distance := 0.
List := {all vertices}.
while List is not empty:
v := remove List vertex with minimum distance.
mark v as known.
for each unknown neighbor n of v:
dist := v's distance + edge (v, n)'s weight.
if dist is smaller than n's distance:
n's distance := dist.
n's previous := v.
reconstruct path from v2 back to v1,
following previous pointers.
Operations on Disjoint Data Sets
• MAKE-SET(u) – creates a new set whose only
member is u
• FIND-SET(u) – returns a representative element
from the set that contains u
– Any of the elements of the set that has a particular
property
– E.g.: Su = {r, s, t, u}, the property is that the element
be the first one alphabetically
FIND-SET(u) = r FIND-SET(s) = r
– FIND-SET has to return the same value for a given set
Operations on Disjoint Data Sets
• UNION(u, v) – unites the dynamic sets that
contain u and v, say Su and Sv
– E.g.: Su = {r, s, t, u}, Sv = {v, x, y}
UNION (u, v) = {r, s, t, u, v, x, y}

• Running time for FIND-SET and UNION depends


on implementation.
• Can be shown to be α(n)=O(lgn) where α() is a
very slowly growing function (see Chapter 21)

You might also like