MUTHAYAMMAL COLLEGE OF ARTS AND SCIENCE (Autonomous), RASIPURAM
DEPARTMENT OF COMPUTER APPLICATIONS
STAFF NAME: Mrs.N.Padmapriya CLASS: II BCA - A PAPER CODE: 23M3UCAC03
PAPER NAME: Data Structures and Algorithms UNIT: IV
GRAPH:
Introduction:
Graph is another non-linear data structure.
It is hierarchical relationship between parent and children’s.
Application:
Airlines
Source-destination network
Konigsberg’s bridges.
Flowchart of a program
Graph Terminology:
Graph:
A graph consist of two sets
(i) A set V called set of all vertices (or node)
(ii) A set E called set of all edges (or arcs)m
Set of vertices = { 1,2,3}
Set of edges={ (1,2),(1,3)}
Digraph:
A digraph is also called a directed graph. If a graph G, such that G=<V,E>, where V is the set of all
vertices and E is the set of ordered pair of elements from V.
Here G2 is a Digraph where
V = {v1, v2, v3, v4}
E = {(v1, v2), (v1, v3), (v2, v3), (v3, v4), (v4, v1)}
Weighted graph:
A graph is termed as weighted graph if all the edges in it are labeled with some weight.
Ex: G3 and G4 are two weighted graphs.
Adjacent vertices:
A vertex vi is adjacent to another vertex say vj if there is an edge from vi to vj.
Ex: Graph G11, v2 is adjacent to v3 and v4.
1
Self loop:
If there is an edge whose starting and end vertices are same, that is (vi,vj) is an edge then it is called a
self loop.
Ex: GraphG5
Parallel edges:
If there are more than one edges between the same pair of vertices, then they are known as the parallel
edge.
Ex: Graph G5.
Multi graph:
A graph which has either self loop or parallel edges or both is called multi graph.
Ex: Graph G5.
Simple graph (digraph):
A graph if it does not have any self loop or parallel edges is called a simple graph.
Ex: graph G5.
Complete graph:
A graph G is said to be complete if each vertex vi adjacent to every other vertex vj in G
Ex: Grapg G6 and G9.
Acyclic graph:
If there is a path containing one or more edges which starts from a vertex vi and terminates into the
same vertex then the path is known as a cycle.
Ex: graph G4 and G7.
Isolated vertex:
A vertex is isolated if there is no edge connected from any other vertex to the vertex.
Ex: Graph G8.
Degree of vertex:
The number of edges connected with vertex vi called the degree of vertex vi and is denoted by degree
(vi).
In digraph there are two degrees: indegree and ourdegree.
Indegree of vi denoted as indegree(vi) = number of edges incident into vi.
Outdegree(vi) = number of edges emanating from vi.
Ex: In graph G4 indegree(v1)=2 outdegree(v1)=1
indegree(v2)=2 outdegree(v1)=0
Pendent vertex:
A vertex vi is pendent if its indegree(vi)=1 and outdegree (vi)=0
Ex: G8 is a pendent vertex.
2
Connected graph:
In a graph G two vertices vI and vj are said to be connected if there is a path in G from vi to vj.
A graph is said to be connected if for every pair of distinct vertices vi, vj in G there is a path.
Ex: Graph G1, G3 and G6.
REPRESENTATION OF GRAPH:
A graph can be represented in many ways
1. Set representation
2. Linked representation
3. Sequential (matrix) representation
(i) Set representation:
This is one of the straightforward methods of representing a graph. In this method two sets are
maintained (i) V is the set of vertices
(ii) E is the set of edges.
Graph G1
V(G1)= { v1,v2,v3,v4,v5,v6,v7}
E(G1)= { ( v1,v2), (v1,v3), (v2,v4), (v2,v5),(v3,v6),(v3,v7)}
Graph G2
V(G2)= { v1,v2,v3,v4,v5,v6,v7}
E(G2)= { ( v1,v2), (v1,v3), (v2,v4), (v2,v5),(v3,v4),(v3,v6), (v4,v7),(v5,v7),(v6,v7)}
Graph G3
V(G3)= { A,B,C,D,E}
E(G3)= { ( A,B), (A,C), (C,B), (C,A),(D,A),(D,B),(D,C),(D,E),(E,B)}
Graph G4
V(G4)= { A,B,C,D}
E(G4)= { ( 3,A,C), (5,B,A), (1,B,C), (7,B,D),(2,C,A),(4,C,D),(6,D,B),(8,D,C)}
3
(ii) Linked representation:
Linked representation is another space-saving way of graph representation.
Node structure is,
Linked representation of graphs, the number of lists depends on the number of vertices in the graph.
The header node in each list maintains a list of all adjacent vertices of anode for which header node is
meant.
iii. Matrix Representation
The adjacency matrix is represents in 2D array of size n*n matrix in which n is the number of vertices.
Ex: A[i][j]=1 means that the adjacency matrix has one edge.
A[i][j]=0 means that the adjacency matrix has no edges.
Adjacency matrix for undirected graph:
The adjacency matrix for an undirected graph is symmetric.
The adjacency matrix for a directed graph need not be symmetric.
The space needed to represent a graph using its adjacency matrix is n2 locations.
OPERATIONS ON GRAPHS
Insertion
To insert a vertex and hence establishing connectivity with other vertices in the existing graph
To insert an edge between vertices in the graph.
Deletion
To delete a vertex from the graph.
To delete an edge from the graph.
4
Merging
To merge two graph G1 and G2 into a single graph.
Traversal
To visit all the vertices in the graph.
Operations on Linked List Representation of Graphs:
In this representation using two representations.
(i) An array of vertices having two fields: LABEL – label for the vertices, LINK-the pointer to the
linked list.
(ii) A linked list to maintain the list of all adjacent vertices for any vertex vi for which it is meant.
(iii) A node structure has two fields other than the filed LINK.
(iv) The first field WEIGHT is to store the weight of the edge and the second field LABLE to store the
vertex’s label
Insertion
Insertion procedure differs for undirected graph and directed graph.
To insert of a vertex into an undirected graph, if Vx is inserted and Vi be its adjacent vertex Vi has to be
incorporated in the adjacency list of Vx as well as has to be incorporated in the adjacency list of Vi.
If it’s a digraph and if there is a path from Vx to Vi we add a node for Vi into the adjacency list of Vx, if
there is an edge from Vi to Vx add a node for Vx in the adjacency list of Vi.
1) Algorithm INSERT_VERTEX_LL_UG(Vx, X)
Vx is the new vertex that has to be inserted into a graph.
Steps:
1. N=N+1, Vx=N
2. For i=1 to l do
1. Let j=X[i]
2. If (j>=N) then
1. Print “No vertex labeled X[i] exist; edge from Vx into the list of vertices.”
3. Else
1. INSERT_SL-END(UGptr[N],x[i])
2. INSERT_SL-END(UGptr[j],Vx
4. Endif
3. Endfor
4. Stop
5
2) Algorithm INSERT_VERTEX_LL_DG(Vx, X,Y)
Vx is the new vertex that has to be inserted into a graph.
Steps:
1. N=N+1, Vx=N
2. For i=1 to m do
1. Let j=X[i]
2. If (j>=N) then
1. Print “No vertex labeled X[i] exist; edge from Vx to X[i] is not established”
3. Else
1. INSERT_SL-END (DGptr[N],x[i])
4. Endif
3. Endfor
4. For i=1 to n do
1. Let j=Y[i]
2. If (j>=N) then
1. Print “No vertex labeled Y[i] exist; edge from Vx to X[i] is not established”
3. Else
1. INSERT_SL-END (DGptr[j],Vx)
4. Endif
5. Endfor
6. stop
3) Insert the edge between two vertices in Undirected graph:
Algorithm: INSERT_EDGE_LL_UG(Vi,Vj)
Insert the edge to be inserted between vertices Vi and Vj.
Steps:
1. Let N=number of vertices in the graph
2. If(Vi>N) or (Vj>N) then
1. Print” Edge is not possible between Vi and Vj”
3. Else
1. INSERT_SL_END (UGptr[Vi],Vj”
2. INSERT_SL_END (UGptr[Vj],Vi”
4. Endif
5. Stop
6
4) Insert the edge between two vertices in directed graph:
Algorithm: INSERT_EDGE_DG (Vi,Vj)
Insert the edge to be inserted between vertices Vi and Vj.
Steps:
1. Let N=number of vertices in the graph
2. If(Vi>N) or (Vj>N) then
1. Print” Edge is not possible between Vi and Vj”
3. Else
1. INSERT_SL_END (UGptr[Vi],Vj”)
4. Endif
5. Stop
Deletion:
1) Delete the vertex:
Algorithm Delete_Vertex_LL_UG (Vx)
Step:
1. If (N=0) then
1. Print” Graph is empty : No deletion”
2. Exit
2. Endif
3. ptr=UGptr[Vx] . LINK
4. While(ptr ≠ NULL) do
1. j=ptr.LABEL
2. DELETE_SL_ANY(UGptr[j],Vx)
3. DELETE_SL_ANY(UGptr[Vx], j)
4. ptr=UGptr[Vx].LINK
5. Endwhile
6. UGptr[Vx].LABEL=NULL
7. UGptr[Vx].LINK=NULL
8. RETURN_NODE(ptr)
9. N=N-1
10. Stop
2) To delete the edge between vertices Vi and Vj
Algorithm: Delete_Edge_LL_UG(Vi,Vj)
7
1. let N=number of vertices in the graph
2. if(Vi>N ) or ( Vj >N) then
1. Print “Vertex does not exist: Error in edge removal”
3. Else
1. DELETE_SL_ANY(UGptr[Vi],Vj)
2. DELETE_SL_ANY(UGptr[Vj],Vi)
4. Endif
5. Stop
GRAPH TRAVESALs:
In the traversal of a binary tree there are two ways as follows.
Depth First search
Breadth first search
Depth First Search:
Depth First Search (DFS) algorithm traverses a 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 S to A to D to G to E to B first, then to
F and lastly to C.
It employs the following rules.
1. Rule 1 − Visit the adjacent unvisited vertex.
2. Mark it as visited.
3. Display it.
4. Push it in a stack.
5. Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack.
6. It will pop up all the vertices from the stack, which do not have adjacent vertices.
8
7. Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
Breadth First Search:
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue 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, BFS algorithm traverses from A to B to E to F first then to C and G
lastly to D. It employs the following rules.
1. Rule 1 − Visit the adjacent unvisited vertex.
2. Mark it as visited.
3. Display it.
4. Insert it in a queue.
5. Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
6. Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
APPLICATION OF GRAPH STRUCTURES:
Graph is an important data structure whose extensive applications are known in almost all application
areas.
Conversion of a particular problem into this general graph theoretic problem will rest on the reader.
1. Shortest path problem
2. Topological sorting of a graph
3. Spanning trees
SHORTEST PATH PROBLEM
The shortest path problem is about finding a path between 2 vertices in a graph such that the total sum
of the edges weights is minimum.
To find shortest problem, we have three algorithm,
9
1. Floyd & Warshall’s Algorithms
2. Dijkstra’s Algorithm
Warshall’s Algorithms:
This is a classical algorithm by which we can determine whether there is a path from any vertex Vi to
another vertex Vj either directly or through one or more intermediate vertices.
Steps:
1. For i=0 to N do
1. For j=1 to N do
1. P[i][j]= Gptr[i][j]
2. Endfor
2. End for
3. For k=1 to N do
1. For i=1 to N do
1. For j=1 to N do
1. P[i][j]= P[i][j] v (P[i][k] ^ P[k][j])
2. Endfor
2. Endfor
4. End for
5. Return(p)
6. Stop
Floyd’s Algorithm:
The basic structure of the Floyd’s algorithm is same as Warshall’s algorithm.
Steps:
1. For i=1 to N do
1. For j=1 to N do
1. If (Gptr[i][i] =0) then
1. Q[i][j]=∞
2. PATHS[i][j]=NULL
2. Else
1. Q[i][j]=Gptr[i][j]
2. P=COMBINE (i,j)
3. PATHS[i][j]=P
3. Endif
2. Endfor
10
2. Endfor
3. For k=1 to N do
1. For i=1 to N do
1. For j=1 to N do
1. Q[i][j]= MIN(Q[i][j], Q[i][k]+ Q[k][j])
2. If (Q[i][k]+ Q[k][j]< Q[i][j]) then
1. p1= PATHS[i][k]
2. p2= PATHS[k][j]
3. PATHS[i][j]=COMBINE(p1,p2)
3. Endif
2. Endfor
2. Endfor
4. End for
5. Return (Q, PATHS)
6. Stop
Dijkstra’s Algorithm:
Dijkstra’s algorithm solves the single-source shortest-paths problem on a directed weighted graph G =
(V, E), where all the edges are non-negative.
Example
Let us consider vertex 1 and 9 as the start and destination vertex respectively.
Initially, all the vertices except the start vertex are marked by ∞ and the start vertex is marked by 0.
Step1 Step2 Step3 Step4 Step5 Step6 Step7 Step8
Vertex Initial
V1 V3 V2 V4 V5 V7 V8 V6
1 0 0 0 0 0 0 0 0 0
2 ∞ 5 4 4 4 4 4 4 4
3 ∞ 2 2 2 2 2 2 2 2
4 ∞ ∞ ∞ 7 7 7 7 7 7
5 ∞ ∞ ∞ 11 9 9 9 9 9
6 ∞ ∞ ∞ ∞ ∞ 17 17 16 16
11
7 ∞ ∞ 11 11 11 11 11 11 11
8 ∞ ∞ ∞ ∞ ∞ 16 13 13 13
9 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ 20
Hence, the minimum distance of vertex 9 from vertex 1 is 20. And the path is
1→ 3→ 7→ 8→ 6→ 9
Topological Sorting:
Topological sorting is an ordering of vertices of a graph, such that if there is a path from u to v in the
graph then u appears before v in the ordering.
A topological ordering is not possible if the graph has a cycle, since for two vertices u and v on the
cycle, u precedes v and v precedes u.
A simple algorithm to find a topological ordering is to find out any vertex with in degree zero, that is
vertex without any predecessor.
Algorithm:
Begin
Initially mark all nodes as unvisited
For all nodes v of the graph, do
If v is not visited, then
TopoSort (i, visited, stack)
Done
Pop and print all elements from the stack
End.
12
MINIMUM SPANNING TREE
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.
A disconnected graph does not have any spanning tree.
There are two methods are efficient:
1. Kruskal’s algorithm
2. Prim’s Algorithm
Kruskal’s Algorithm:
Kruskal's algorithm to find the minimum cost spanning tree uses the greedy approach.
This algorithm treats the graph as a forest and every node it has as an individual tree.
A tree connects to another only and only if, it has the least cost among all available options and does
not violate MST properties.
To understand Kruskal's algorithm let us consider the following example −
Step 1 - Remove all loops and Parallel Edges
Remove all loops and parallel edges from the given graph.
Step 2 - Arrange all edges in their increasing order of weight
The next step is to create a set of edges and weight, and arrange them in an ascending order of
weightage (cost).
13
Step 3 - Add the edge which has the least weightage
Now we start adding edges to the graph beginning from the one which has the least weight.
In case, by adding one edge, the spanning tree property does not hold then we shall consider not
including the edge in the graph.
The least cost is 2 and edges involved are B, D and D,T.
We add them. Adding them does not violate spanning tree properties, so we continue to our next edge
selection.
Next cost is 3, and associated edges are A,C and C,D. We add them again −
Next cost in the table is 4, and we observe that adding it will create a circuit in the graph. −
We ignore it. In the process we shall ignore/avoid all edges that create a circuit.
We observe that edges with cost 5 and 6 also create circuits.
We ignore them and move on.
Now we are left with only one node to be added.
Between the two least cost edges available 7 and 8, we shall add the edge with cost 7.
14
By adding edge S, A we have included all the nodes of the graph and we now have minimum cost
spanning tree.
Prim’s Algorithm:
Prim's algorithm to find minimum cost spanning tree.
Prim's algorithm, treats the nodes as a single tree and keeps on adding new nodes to the spanning tree
from the given graph.
Example −
Step 1 - Remove all loops and parallel edges
Remove all loops and parallel edges from the given graph.
In case of parallel edges, keep the one which has the least cost associated and remove all others.
Step 3 - Check outgoing edges and select the one with less cost
After choosing the root node S, we see that S, A and S,C are two edges with weight 7 and 8,
respectively. We choose the edge S, A as it is lesser than the other.
Now, the tree S-7-A is treated as one node and we check for all edges going out from it
15
We select the one which has the lowest cost and include it in the tree.
After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the
edges again.
However, we will choose only the least cost edge.
In this case, C-3-D is the new edge, which is less than other edges' cost 8, 6, 4, etc.
After adding node D to the spanning tree, we now have two edges going out of it having the same
cost, i.e. D-2-T and D-2-B.
Thus, we can add either one.
But the next step will again yield edge 2 as the least cost.
Hence, we are showing a spanning tree with both edges included.
Bi – connectivity graph:
An undirected graph is called Biconnected if there are two vertex-disjoint paths between any two
vertices. In a Biconnected Graph, there is a simple cycle through any two vertices.
By convention, two nodes connected by an edge form a biconnected graph, but this does not verify the
above properties. For a graph with more than two vertices, the above properties must be there for it to
be Biconnected.
Or in other words:
A graph is said to be Biconnected if:
It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path.
Even after removing any vertex the graph remains connected.
Following are some examples:
16
17
How to find if a given graph is Biconnected or not?
A connected graph is Biconnected if it is connected and doesn’t have any Articulation Point. We mainly
need to check two things in a graph.
1. The graph is connected.
2. There is not articulation point in graph.
We start from any vertex and do DFS traversal. In DFS traversal, we check if there is any articulation
point. If we don’t find any articulation point, then the graph is Biconnected. Finally, we need to check
whether all vertices were reachable in DFS or not. If all vertices were not reachable, then the graph is not
even connected.
Cut vertex Euler circuit:
A cut vertex (or articulation point) is a vertex in a connected graph that, if removed along with its
incident edges, increases the number of connected components of the graph. Identifying cut vertices
can be crucial for understanding the vulnerabilities in networks.
An Euler circuit (or Eulerian circuit) is a trail in a graph that visits every edge exactly once and
returns to the starting vertex. For a graph to have an Euler circuit, it must be connected and all
vertices must have even degrees.
Relationship Between Cut Vertices and Euler Circuits
1. Euler Circuits and Cut Vertices:
o If a graph has an Euler circuit, it cannot have any cut vertices. This is because removing a
cut vertex would disconnect the graph, making it impossible to traverse all edges and return to the
starting point without revisiting some edges.
2. Finding Cut Vertices:
o A common algorithm to find cut vertices is Tarjan's Algorithm, which uses Depth-First
Search (DFS) and keeps track of discovery and low values to identify articulation points.
18
3. Identifying Euler Circuits:
o To check for the existence of an Euler circuit, you can perform the following steps:
Check if the graph is connected.
Verify that all vertices have even degrees.
Key Points
Cut Vertices:
o They indicate critical points in network connectivity.
o They can disrupt the traversal of edges if the vertex is part of the Euler circuit.
Euler Circuits:
o These highlight paths that can traverse every edge.
o Their existence implies robustness against disconnection caused by removing any single
vertex.
Applications
In network design, understanding cut vertices helps in building resilient systems.
Euler circuits are often used in routing problems, such as in garbage collection routes or mail
delivery paths.
Example Graph:
Consider the following undirected graph:
/\
B C
/\ \
D E---F
\/
19
Identifying Cut Vertices
1. Cut Vertices:
o Vertex A: Removing A disconnects B, C, D, E, F, and G from each other.
o Vertex B: Removing B disconnects D and E from A and C.
o Vertex C: Removing C disconnects F from the rest of the graph.
Thus, the cut vertices in this graph are A, B, and C.
Checking for an Euler Circuit
To check for an Euler circuit, we need to verify:
1. All vertices have even degree:
o A (degree 2)
o B (degree 3)
o C (degree 2)
o D (degree 2)
o E (degree 3)
o F (degree 2)
o G (degree 2)
Since vertices B and E have odd degrees, this graph does not have an Euler circuit.
Cut Vertices: A, B, and C are cut vertices; their removal increases the number of connected components.
Euler Circuit: The graph does not have an Euler circuit since not all vertices have even degrees.
20