CS23231 DS Unit IV Reg 2023
CS23231 DS Unit IV Reg 2023
GRAPHS
CHAPTER - 1 - GRAPHS
1.1 INTRODUCTION
A graph G = (V, E) consists of a set of vertices, V, and a set of edges, E. Vertices are
referred to as nodes. Each edge is a pair (v, w), where v, w V i.e. v = V 1, w = V2. Edges are
sometimes referred to as arcs.
Example
Here V1, V2, V3 and V4 are vertices and (V1, V2), (V1, V3), (V1, V4), (V2, V3), (V2, V4) and
(V3, V4) are edges.
Directed graph is a graph which consists of directed edges, where each edge in E is
unidirectional. It is also referred as Digraph. If (v, w) is a directed edge then (v, w) ≠ (w, v).
A graph is said to be weighted graph if every edge in the graph is assigned a weight or
value. It can be directed or undirected graph.
An undirected graph, in which every vertex has an edge to all other vertices is called a
complete graph. A complete graph with n vertices has n(n-1)/2 edges.
Example
If there is a path from every vertex to every other vertex in a directed graph, then it is said
to be strongly connected graph. Otherwise, it is said to be weakly connected graph.
Example
Strongly Connected Weakly Connected
1.2.7 Path
A path in a graph is a sequence of vertices w 1, w2, w3, . . . , wn such that (wi, wi+1) E for 1
< i < N.
Example
1.2.8 Length
The length of a path is the number of edges on the path, which is equal to N – 1, where N
represents the number of vertices.
Example
In Fig. the length of the path V1, to V3, is 2 i.e., (V1, V2), (V2, V3).
1.2.9 Loop
If the graph contains an edge (v, v) from a vertex to itself, then the path is referred to as a
loop.
1.2.10 Cycle
A cycle in a graph is a path in which first and last vertex are the same. A graph which has
cycles is referred to as cyclic graph.
1.2.11 Degree
The number of edges incident on a vertex determines its degree. The degree of the vertex
V written as degree (V).
1.2.12 Indegree
The indegree of the vertex V, is the number of edges entering into the vertex V.
Example
Indegree (V1) = 2.
1.2.13 Outdegree
The out degree of the vertex V is the number of edges exiting from that vertex V.
Example
Outdegree (V1) = 1.
1.2.14 Acyclic
2.1 INTRODUCTION
• Adjacency Matrix
• Adjacency list
The adjacency matrix A for a graph G = (V, E) with n vertices is an n x n matrix, such that:
Example-1
Example-2
Example-3
2.2.2 Adjacency Matrix for Undirected Graph
Example
Advantage
Simple to implement.
Disadvantage
In this representation, store a graph as a linked structure. We store all vertices in a list and
then for each vertex, have a linked list of its adjacency vertices.
Example
Disadvantages
It takes 0(n) time to determine whether there is an arc from vertex i to vertex j. Since there
can be 0(n) vertices on the adjacency list for vertex i.
CHAPTER - 3 - GRAPH TRAVERSALS
3.1 INTRODUCTION
A graph traversal is a systematic way of visiting the nodes in a specific order. There are
two types of graph traversal:
Breadth First Search (BFS) of a graph G starts from an unvisited vertex u. Then all
unvisited vertices vi adjacent to u are visited and then all unvisited vertices w j adjacent to vi are
visited and so on. The traversal terminates when there are no more nodes to visit. Breadth first
search uses a queue data structure to keep track of the order of nodes whose adjacent nodes are to
be visited.
3.2.1 Algorithm
Step 1: Choose any node in the graph, designate it as the search node and mark it as
visited.
Step 2: Using the adjacency matrix of the graph, find all the unvisited adjacent nodes to
the search node and enqueue them into the queue Q.
Step 3: Then the node is dequeued from the queue. Mark that node as visited and designate
it as the new search node.
Step 5: This process continues until the queue Q which keeps track of the adjacent nodes is
empty.
void BFS(vertex u)
{
Initialize Q; visited[u] =
1; Enqueue(u, Q);
while (!Isempty(Q)) {
u = Dequeue(Q);
print u;
for all vertices v adjacent to u
{
if (visited[v] == 0)
{
Enqueue(v, Q)
visited[v] = 1;
}
}
}
}
3.2.3 Example
3.2.4 Implementation
2. Find the adjacent unvisited vertices of 'A' and enqueue then' into the queue. Here B and
C are adjacent nodes of A and B and C are enqueued.
3. Then vertex 'B' is dequeued and its adjacent vertices C and D are taken from the
adjacency matrix for enqueuing. Since vertex C is already in the queue, vertex D alone
is enqueued.
4. Then vertex 'C' is dequeued and its adjacent vertices A, B and D are found out. Since
vertices A and B are already visited and vertex D is also in the queue, no enqueue
operation takes place.
Here C is dequeued.
5. Then vertex 'D' is dequeued. This process terminates as all the vertices are visited and
the queue is also empty.
Depth first works by selecting one vertex V of G as a start vertex; V is marked visited.
Then each unvisited vertex adjacent to V is searched in turn using depth first search recursively.
This process continues until a dead end (i.e) a vertex with no adjacent unvisited vertices is
encountered. At a deadend, the algorithm backsup one edge to the vertex it came from and tries to
continue visiting unvisited vertices from there.
The algorithm eventually halts after backing up to the starting vertex, with the latter being
a dead end. By then, all the vertices in the same connected component as the starting vertex have
been visited. If unvisited vertices still remain, the depth first search must be restarted at any one of
them.
3.3.1 Algorithm
Step 1: Choose any node in the graph. Designate it as the search node and mark it as
visited.
Step 2: Using the adjacency matrix of the graph, find a node adjacent to the search node
that has not been visited yet. Designate this as the new search node and mark it as visited.
Step 3: Repeat step 2 using the new search node. If no nodes satisfying (2) can be found,
return to the previous search node and continue from there.
Step 4: When a return to the previous search node in (3) is impossible, the search from the
originally chosen search node is complete.
Step 5: If the graph still contains unvisited nodes, choose any node that has not been
visited and repeat step (1) through (4).
3.3.2 Routine for DFS
void DFS(Vertex V)
{
visited[V] = True;
for each W adjacent to V
if(!visited [W])
DFS(W);
}
3.3.3 Example
3.3.4 Implementation
4.1 INTRODUCTION
A topological sort is an ordering of vertices in a directed acyclic graph, such that if there is
a path from Vi to Vj, then Vj appears after Vi in the ordering.
A topological ordering is not possible if the graph has a cycle, since for two vertices v and
w on the cycle, v precedes w and w precedes v. Furthermore, the ordering is not necessarily
unique; any legal ordering will do. In the graph in Figure v1, v2, v5, v4, v3, v7, v6 and v1, v2, v5,
v4, v7, v3, v6 are both topological orderings.
4.2 ALGORITHM
A simple algorithm to find a topological ordering is first to find any vertex with no
incoming edges. We can then print this vertex, and remove it, along with its edges, from the
graph. Then we apply this same strategy to the rest of the graph.
To implement the topological sort, perform the following steps.
Step 3: Dequeue the vertex v and decrement the indegree of all its adjacent vertices.
Step 4: Enqueue the vertex on the queue if its indegree falls to zero.
Step 6: The topological ordering is the order in which the vertices dequeue.
/* Assume thatt the graph is read into an adjacency matrix and that the indegrees are
computed for every vertices and placed in an array (i.e. Indegree [ ] ) */
voidTopsort (Graph G)
{
Queue Q; int
counter = 0;
Vertex V, W;
Q = CreateQueue (NumVertex);
Makeempty (Q); for each
vertex V if (indegree [V] ==
0)
Enqueue (V, Q);
while (! IsEmpty (Q))
{
V = Dequeue (Q);
TopNum[V] = ++counter;
for each W adjacent to V if (--
Indegree [W] == 0)
Enqueue (W, Q);
}
if (counter != NumVertex)
Error (" Graph has a cycle");
DisposeQueue (Q); /* Free the Memory */
}
4.4 EXAMPLE
v1 v2 v3 v4 v5 v6 v7
v1 v2 0 1 1 1 0 0 0
v3 v4 0 0 0 1 1 0 0
v5 v6
0 0 0 0 0 1 0
v7
0 0 1 0 0 1 1
0 0 0 1 0 0 1
0 0 0 0 0 0 0
0 0 0 0 0 1 0
Step 1:
Number of 1's present in each column of adjacency matrix represents the indegree of the
corresponding vertex.
Dequeue the vertex v1 from the queue and decrement the indegree of its adjacent vertex
v2, v3 and v4.
Hence, Indegree [v2] = 0 Indegree [v3] = 1 Indegree [v4] = 2
Step 4:
Dequeue the vertex v2 from the queue and decrement the indegree of its adjacent vertex v4
and v5.
Step 5:
Dequeue the vertex v5 from the queue and decrement the indegrees of its adjacent vertex
v4 and v7.
Step 6:
Dequeue the vertex v4 from the queue and decrement the indegrees of its adjacent vertex
v3, v6 and v7.
Now, enqueue the vertex v3 and v7 in any order as its indegree falls to zero.
Step 7:
Dequeue the vertex v3 from the queue and decrement the indegrees of its adjacent vertex
v6.
Step 7:
Dequeue the vertex v7 from the queue and decrement the indegrees of its adjacent vertex
v6.
Step 8:
Step 9:
As the queue becomes empty, topological ordering is performed, which is nothing but, the
order in which the vertices are dequeue.
Vertex 1 2 3 4 5 6 7
V1 0 0 0 0 0 0 0
V2 1 0 0 0 0 0 0
V3 2 1 1 1 0 0 0
V4 3 2 1 0 0 0 0
V5 1 1 0 0 0 0 0
V6 3 3 3 3 2 1 0
V7 2 2 2 1 0 0 0
Enqueue v1 v2 v5 v4 v3, v7 v6
Dequeue v1 v2 v5 v4 v3 v7 v6
Analysis
The running time of this algorithm is O (|E| + |V|), where E represents the Edges and V
represents the vertices of the graph.
CHAPTER - 5 - SINGLE SOURCE SHORTEST PATH
5.1 INTRODUCTION
Given as input a weighted graph, G = (V, E), and a distinguished vertex, s, find the shortest
weighted path from s to every other vertex in G.
The general method to solve the single source shortest path problem is known as Dijkstra's
algorithm. This is applied to the weighted graph G.
Dijkstra's algorithm is the prime example of Greedy technique, which generally solve a
problem in stages by doing what appears to be the best thing at each stage. This algorithm
proceeds in stages, just like the unweighted shortest path algorithm. At each stage, it selects a
vertex v, which has the smallest dv among all the unknown vertices, and declares that as the
shortest path from S to V and mark it to be known. We should set dw = dv + Cvw, if the new
value for dw would be an improvement.
5.3 ROUTINE
5.4 Example
Then the adjacent vertices of a is found and its distance are updated as follows :
Now, select the vertex with minimum distance, which is not known and mark that vertex
as visited.
Here d is the next minimum distance vertex. The adjacent vertex to d is c, therefore, the
distance of c is updated a follows:
Since the adjacent vertex d is already visited, select the next minimum vertex c and mark it
as visited.
CHAPTER - 6 - MINIMUM SPANNING TREE
6.1 INTRODUCTION
A spanning tree of a connected graph is its connected a cyclic subgraph that contains all
the vertices of the graph.
A minimum spanning tree of a weighted connected graph G is its spanning tree of the
smallest weight, where the weight of a tree is defined as the sum of the weights on all its edges.
The total number of edges in Minimum Spanning Tree (MST) is |V| - 1 where V is the number of
vertices. A minimum spanning tree exists if and only if G is connected. For any spanning Tree T,
if an edge e that is not in T is added, a cycle is created. The removal of any edge on the cycle
reinstates the spanning tree property.
Prim's algorithm is one of the way to compute a minimum spanning tree which uses a
Greedy technique. This algorithm begins with a set U initialised to {1}. It then grows a spanning
tree, one edge at a time. At each step, it finds a shortest edge (u, v) such that the cost of (u, v) is
the smallest among all edges, where u is in Minimum Spanning Tree and V is not in Minimum
Spanning Tree.
5.3 ROUTINE
6.4 Example
Fig. Undirected Graph G
T[b].dist = Min(T[b].Dist, C )
=2
T[d].dist = Min(T[d].Dist, C )
=1
T[c].dist = Min(T[c].Dist, C )
=3
Next, the vertex with minimum cost 'c' is marked as visited and the distance of its
unknown adjacent vertex is updated.
Since, there is no unknown vertex adjacent to 'c', there is no updation in the distance.
Finally, the vertex 'b' which is not visited is marked.
Fig. (a) After the vertex 'b'
is marked visited, the algorithm
terminates
Fig. (f)
Minimum Spanning Tree
Tree is 4 [i.e. Ca,b + Ca,d + Cc,d]