Unit 5 – Week 13
GRAPH DATA STRUCTURE
Graph Terminology - Representation of graph using Arrays, Linked List - Graph Traversal using BFS,
DFS - Topological Sorting
Week 13
Learning Objectives:
1. Utilize algorithms to find shortest data search in graphs for real-time application development
2. Create graph data structure, evaluate its operations, implement algorithms to identify shortest path
Key Topics
1. Introduction – Graph Terminology
2. Representation of graph
1. Adjacency Matrix Representation (Array Representation)
2. Adjacency List representation
3. Graph Traversal Algorithm
1. Breadth First Search (BFS) Traversal Algorithm
2. Depth First Search (DFS) Traversal Algorithm
4. Topological Sorting
5. Summary
5.1 Introduction - Graph Terminology
Graph: Graph G is a pair (V, E), where V is a finite set of vertices and E is a finite
set of edges. We will often denote n = |V|, e = |E|.
o Vertices: A graph is generally displayed as Figure 5.1, in which the vertices
are represented by circles and the edges by lines.
o Edge: An edge with an orientation (i.e., arrow head) is a directed edge, while
an edge with no orientation is our undirected edge.
Undirected Graph: If all the edges in a graph are undirected, then the graph is an
undirected graph. The graph in Figure 5.1(a) is an undirected graph. If all the edges
are directed; then the graph is a directed graph.
Directed graph: A directed graph is also called as digraph. A graph G is connected
if and only if there is a simple path between any two nodes in G. For example, the
graph of Figure 5.1(b) is a directed graph.
Complete Graph: A graph G is said to be complete if every node in G is adjacent
to every other node in G. A complete graph with n nodes will have n (n-1)/2 edges.
For example, Figure 5.1.(a) and Figure 5.1.(d) are complete graphs.
Connected or Strongly Connected Graph: A directed graph G is said to be
connected, or strongly connected, if for each pair (u, v) for nodes in G there is a
path from u to v and also a path from v to u. On the other hand, G is said to be
unilaterally connected if for any pair (u, v) of nodes in G there is a path from u to v
or a path from v to u. For example, the digraph shown in Figure 5.1 (e) is strongly
connected.
Figure 5.1 E∈xamples of various Graphs
Path: A path in the graph is a sequence of vertices V1, V2, …Vn such that Vi, Vi+1 ∈ E.
For example, the graph shown in Figure 5.1 (c), path from V1 to V4 i.e. V1, V2, V3, V4.
Weighted Graph: A weighted graph is a graph if every edge in the graph is assigned
with a weight or value. It can be either directed or undirected graph.
(a) Undirected Weighted Graph (b) Directed Weighted Graph
Degree: The number of incoming edges to a vertex v is called in–degree of the vertex
(denote indeg(v)). The number of outgoing edges from a vertex is called out-degree
(denote outdeg(v)). For example, let us consider the digraph shown in Figure 5.1(f),
indegree(v1) = 2 outdegree(v1) = 1
indegree(v2) = 2 outdegree(v2) = 0
Length of the Path: Length of the path is the number of edges on the path, which is
equal to n-1, where n represents the number of vertices.
Loop: If Graph contains an edge (u, v) from a vertex to itself, then the path is referred
to as loop.
Cycle Graph: A simple graph of ‘n’ vertices (n>=3) and n edges forming a cycle of
length ‘n’ is called as a cycle graph. In a cycle graph, all the vertices are of degree 2.
In the below example graphs, each vertex is having degree 2. Therefore, they are
cycle graphs.
Cyclic Graph: A graph containing at least one cycle in it is called as a cyclic graph.
Here, this graph contains two cycles in it. Therefore, it is a cyclic graph.
Acyclic Graph: A graph not containing any cycle in it is called as an acyclic graph.
Here, this graph do not contain any cycle in it. Therefore, it is an acyclic graph.
5.2 Representation of graph
There are two ways of representing graphs. They are:
• Adjacency matrix representation
• Adjacency List representation
5.2.1 Adjacency Matrix Representation (Array Representation)
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 1 if there exists an edge between Vi and Vj.
An undirected graph and its adjacency matrix representation is shown in 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.
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 V i to Vj. 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.
The weighted directed graph along with the adjacency matrix representation is shown in the
following figure.
5.2.2 Adjacency List 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.
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.
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.
5.3 Graph Traversal Algorithm
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. Let’s discuss each one
of them in detail.
o Breadth First Search (BFS) Traversal Algorithm
o Depth First Search (DFS) Traversal Algorithm
5.3.1 Breadth First Search (BFS) Traversal Algorithm
Breadth first search is a graph traversal algorithm that starts traversing the graph from
root node and explores all the neighbouring nodes. Then, it selects the nearest node and explore
all the unexplored nodes. The algorithm follows the same process for each of the nearest node
until it finds the goal.
The algorithm of breadth first search is given below. The algorithm starts with
examining the node ‘S’ and all of its neighbours. In the next step, the neighbours of the nearest
node of ‘S’ are explored and process continues in the further steps. The algorithm explores all
neighbours of all the nodes and ensures that each node is visited exactly once and no node is
visited twice. 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 steps,
Step 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a
queue.
Step 2 − If no adjacent vertex is found, remove the first vertex from the queue.
Step 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
Algorithm:
void BFS (Graph G)
{
Queue Q;
Vertex V, W;
Q=CreateQueue (NumofVertex);
MakeEmpty (Q);
Visited [V]=1;
Enqueue (V, Q);
While (! IsEmpty (Q))
{
V=Dequeue(Q)
Print V;
For all vertices W adjacent to V
If ( Visited [W] ==0) then
{
Enqueue (W, Q);
Visited [W]=1;
}
}
}
Example:
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm
keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the
algorithm is over.
5.3.2 Depth First Search (DFS) Traversal Algorithm
Depth first search works by selecting one vertex V of graph G as start vertex. Make it
as visited. Then each unvisited vertex adjacent to V is searched in turn using depth first search.
This process continues until a dead end i.e. a vertex with no adjacent unvisited vertices are
encountered. At the dead end, algorithm backs up one edge to the vertex it came from and tries
to continue visiting unvisited vertices from there.
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 steps.
1. Create an empty stack
2. Push the start vertex into the stack
3. Pop a vertex from stack. If it is unvisited mark it as visited.
4. Find all adjacent vertices W to the popped vertex V
5. If the adjacent vertex is unvisited, push it into the stack.
6. Repeat from Step 3 until stack becomes empty.
Algorithm:
void DFS (Graph G, Stack s)
{
Stack S;
Vertex V, W;
S=CreateStack (NumOfVertex);
MakeEmpty (S);
S.push(s);
While (! IsEmpty (S))
{
V=S.pop();
if (! Visied [V])
Visted[V]=1;
for all W adjacent to V
if (! Visited [W])
S.push(W);
}
}
Example:
5.4 Topological Sorting
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. Topological ordering is
not possible if graph has cycle. Steps to perform topological sort:
Step 1: Find the indegree for each vertex.
Step 2: Place the vertices whose indegree is 0 on empty queue.
Step 3: Dequeue a vertex V and decrement the indegree’s of all its adjacent vertices.
Step 4: Enqueue the vertex on queue, if its indegree falls to zero.
Step 5: Repeat from Step 3 until queue becomes empty. Topological ordering is the order in
which the vertices are dequeued.
Algorithm:
void TopSort (Graph G)
{
Queue Q;
Vertex V, W;
int count=0;
Q=CreateQueue(NumOfVertex);
MakeEmpty(Q);
For each Vertex V
if (indegree[V]==0)
Enqueue(V,Q);
While (! IsEmpty(Q))
{
V=Dequeue(Q);
Count++;
For each W adjacent to V
If (--indegree[W]==0)
Enqueue(W,Q);
}
if (count != NumOfVertex)
Error(“Graph has cycle”)
DisposeQueue(Q);
}
Example:
Find the number of different topological orderings possible for the given graph-
Solution:
The topological orderings of the above graph are found in the following steps-
Step 1: Write in-degree of each vertex-
Step 2: Vertex-A has the least in-degree. So, remove vertex-A and its associated edges.
Now, update the in-degree of other vertices.
Step 3: Vertex-B has the least in-degree. So, remove vertex-B and its associated edges.
Now, update the in-degree of other vertices.
Step 4: There are two vertices with the least in-degree. So, following 2 cases are possible-
In case-01,
Remove vertex-C and its associated edges.
Then, update the in-degree of other vertices.
In case-02,
Remove vertex-D and its associated edges.
Then, update the in-degree of other vertices.
Step 5: Now, the above two cases are continued separately in the similar manner.
In case-01,
Remove vertex-D since it has the least in-degree.
Then, remove the remaining vertex-E.
In case-02,
Remove vertex-C since it has the least in-degree.
Then, remove the remaining vertex-E.
Conclusion:
For the given graph, following 2 different topological orderings are possible-
ABCDE
ABDCE
5.5 Summary
These topics summarizes about basics of Graph data structure, which is utilized to find shortest data
search in graphs for real-time application development and also create graph data structure, evaluate
its operations, implement algorithms to identify shortest path.
Questions and Exercises
1. Define Graph
2. Define adjacent nodes.
3. What is a directed graph?
4. What is an undirected graph?
5. Name the different ways of representing a graph.
6. Differentiate BFS and DFS.
References
1. Seymour Lipschutz, (2014), “Data Structures with C”, McGraw Hill Education, Special Indian
Edition.
2. SRD Group, (2013), “Data structures using C”,McGraw Hill, 2nd Edition.
3. R.F.Gilberg, B.A.Forouzan, (2005), “Data Structures”, Thomson Indi, 2nd Edition.
4. A.V.Aho, J.E Hopcroft , J.D.Ullman, (2003), “Data structures and Algorithms”, 1st Edition,
Pearson Education.
5. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, 2nd Edition, Pearson
Education.
6. ReemaThareja, (2011), “Data Structures Using C”, 1st Edition, Oxford Higher Education.