Module 5 1
Module 5 1
Graphs
Graphs are primal data structures used in computers & scientific discipline to represent a wide
range of relationships and connections between objects. Graph terminology belong of various
terms and concepts used to describe and analyze graphs. Here are some key graph terminology
and definitions:
1. A Graph is an Order pair Graph = (VS, ES) comprises a set VS of nodes or vertices and a
set of edges ES. An edge has starting node and ending node from VS.
9. Complete graph
Complete graph is a one in which every pair of node links are adjacent
18. If we remove all the cycles from a Graph, it becomes a tree, and if we remove any edge
in the tree, it will become a forest.
19. Subgraph: A subgraph is a graph formed by selecting a subset of vertices and a subset of
edges from a larger graph. It preserves the relationships between the selected vertices.
20. Adjacency Matrix (AM): AM is a square matrix used for representing a graph. It is a n by
n square matrix, where n represents the number of nodes. The cell value at ith row and jth
columnj shows whether an edge between ith node and jth node exists or not. For every
pair of nodes, AM keeps a value 1/0/edge-weight to specify whether the edge exists or
not. It requires n2 space. They can be efficiently used only when the graph is dense.
21. Adjacency List: An adjacency list is a data structure that represents a graph by storing a
list of neighbors for each vertex. It's often more memory-efficient than an adjacency
matrix, especially for sparse graphs. Each vertex in the graph is linked to a set of its
neighboring vertices or edges, meaning that each vertex maintains a list of adjacent
vertices. The specific representation of the adjacency list can vary depending on the
implementation.
22. Operations on Graph Data Structure
Following are the basic graph operations in graph data structure:
Add Node, Remove Node – Insert or Delete a node in a graph. (Insert/Delete
Vertex)
Add edge, Remove Edge – Insert or Delete an edge between two nodes.
(Insert/Delete Edge)
Check if the graph contains a given value (Search or Lookup)
Find path – Discover a path to a destination node from source node. (Find Path)
Inserting a Vertex into a Graph:
Example Graph (G) and its Adjacency Matrix: Call this graph as original graph.
Adjacency Matrix
1 2 1 2 3 4
1 0 1 1 0
2 1 0 1 1
3 0 0 0 1
3 4 4 0 0 0 0
Insert Vertex 5 in to graph (G) and show the changes to Adjacency Matrix
(addVertex(Vn)):
Adjacency Matrix
1 2 1 2 3 4 5
1 0 1 1 0 0
2 1 0 1 1 0
3 0 0 0 1 0
3 4 4 0 0 0 0 0
5 0 0 0 0 0
5
Delete Vertex 3 in original graph (G) and show the changes to Adjacency Matrix
(deleteVertex(Vn)):
Adjacency Matrix
1 2 1 2 4
1 0 1 0
2 1 0 1
4 4 0 0 0
Insert Edge from Vertex 4 to Vertex 2 into original graph (G) and show the changes to
Adjacency Matrix (addEdge(Vs, Ve)):
Adjacency Matrix
1 2 1 2 3 4
1 0 1 1 0
2 1 0 1 1
3 0 0 0 1
3 4 4 0 1 0 0
Delete Edge from Vertex 2 to Vertex 1 in original graph (G) and show the changes to
Adjacency Matrix (deleteEdge(Vs, Ve)):
Adjacency Matrix
1 2 1 2 3 4
1 0 1 1 0
2 0 0 1 1
3 0 0 0 1
3 4 4 0 0 0 0
2. Depth-First Search (DFS): This is another traversal operation that traverses the graph
vertically. It starts with the root node of the graph and investigates each branch as far
as feasible before backtracking.
// Algorithm for BFS():
Explanation:
1. The program starts by defining a structure for a queue that will be used for the BFS
traversal. The queue is implemented as an array-based data structure.
2. A structure for the graph is defined, including the number of vertices and an adjacency
matrix to represent the graph.
3. Functions for creating a graph, adding edges, and performing BFS are defined.
4. In the BFS function, we use a visited array to keep track of visited vertices. A queue is used
to keep track of the vertices to be explored. We start with the startVertex and enqueue it.
Then, we enter a loop where we dequeue a vertex, mark it as visited, and enqueue its
unvisited neighbors. This process continues until the queue is empty.
5. In the main function, a sample graph is created and edges are added to it. The BFS
traversal is initiated with a starting vertex (in this case, vertex 0).
6. The BFS traversal is performed and the nodes are printed in the order they were visited,
demonstrating the breadth-first exploration of the graph.
//Algorithm for DFS()
Step1. Initialise all the links to ready state ( set STATUS = 1)
Step2. Put opening node onto STACK and modify its status as waiting (set
STATUS = 2)
Step 3: Repeat Step 4 and Step 5 till STACK becomes BLANK
Step 4: Remove topmost node on STACK and Process the node. Then modify its
state as processed (set STATUS = 3)
Step 5: Add all neighbors of the node which are in ready state (i.e., STATUS = 1)
to the STACK and modify their state to waiting (set STATUS = 2)
Step 6: Quit.
Implementation of DFS using C:
int pop(struct Stack* s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
return s->items[s->t--];
}
// Iterative DFS
void DepthFirstSearch(struct Graph* g, int startVertex) {
bool visited[g->V];
for (int m = 0; m < g->V; m++) {
visited[m] = false;
}
visited[startVertex] = true;
printf("Depth First Traversal starting from vertex %d:\n", startVertex);
printf("%d ", startVertex);
push(s, startVertex);
while (!isEmpty(s)) {
int currentVertex = s->items[s->top];
int found = 0;
for (int m = 0; m < g->V; m++) {
if (g->adjMatrix[currentVertex][m] == 1 && !visited[m]) {
printf("%d ", m);
visited[m] = true;
push(s, m);
found = 1;
break;
}
}
if (!found) {
pop(s);
}
}
}
int main() {
int V = 7;
struct Graph* g = createGraph(V);
edgeAdd(g, 0, 1);
edgeAdd(g, 0, 2);
edgeAdd(g, 1, 3);
edgeAdd(g, 1, 4);
edgeAdd(g, 2, 5);
edgeAdd(g, 2, 6);
DepthFirstSearch(g, 0);
return 0;}
Explanation:
1. The program starts by defining a structure for a stack, which is used for managing the
depth-first traversal.
2. A structure for the graph is defined, including the number of vertices and an adjacency
matrix to represent the graph.
3. Functions for creating a graph, adding edges, and performing DFS are defined.
4. The DFS function performs an iterative depth-first traversal. It uses a stack to manage the
order of node exploration, starting from the specified source vertex (in this case, vertex
0).
5. The main function creates a sample graph, adds edges to it, and initiates the DFS
traversal starting from vertex 0.
6. The DFS traversal is performed iteratively, and the nodes are printed in the order they are
visited, demonstrating the depth-first exploration of the graph.
24. Shortest Paths and Minimum Spanning Trees
Spanning trees is a sub graph that connects all nodes of a given graph using minimum
number of edges. It may or may not be weighted and does not have cycles.
Spanning trees of any connected undirected graph is a sub-graph, i.e., a tree that binds all
nodes that contribute to minimization of amount of the weights of the edges.
Properties:
A spanning trees can exist if a graph is connected. Otherwise many spanning trees
called forest exists.
The number of edges in a spanning tree = e-1, where e= number of nodes a given
graph.
Cayleys formula: measure of spanning trees in a complete undirected graph
having n nodes Kn = nn-2.
For the K3 graph, total number of spanning trees = 33-2 = 3.
The Shortest path:
Sum of the weights on edges in shortest path (i.e. ABDE) of any pair of vertices (say
between A and E) is minimum among all possible paths between that pair of nodes.
(i.e., A and E).
Computing shortest path can be done for directed, undirected or mixed graphs.
The problem for discovering a shortest path is classified as
o Single-source the shortest path: Here the calculation of shortest path is done
from given source node to every other node of the graph.
o Single-destination the shortest path: Here the computation of shortest path is
done from all nodes of a graph to the given destination node.
o All pairs the shortest path: Here the calculation of shortest path is done for
each pair of nodes.
Prim’s Algorithm: This algorithm is to get least cost Spanning Tree for a undirected connected
graph:
Let G1=(V1, E1) be an connected undirected graph and T1=(V1, E1’) is sub-graph of G1 and is
the spanning Tree for G1 if T1 is a Tree.
Prim(G)
Begin
E’= Փ;
Choose a least cost edge (u1, v1) from E1;
V1’ = {u1};
While V1’ ≠ V1 do
Let (u1, v1) be a least cost edge such that u1 is in V1’ and v1 is in V1 –
V1’;
Add edge (u1, v1) to set E1’;
Add v1 to set V1’
End while
End Prim
Example Graph:
1
6 7
2 1 4
5 5
3
3 2
6 4
5 6
6
Take edge (7,4): Inclusion of this edge causes a loop. Hence discard it.
Take edge (4,5): No loop is formed. Hence include it.
Take edge (5,7): Inclusion of this edge causes a loop. Hence discard it.
Take edge (5,6): No loop is formed. Hence include it.
Dijkstra's Algorithm:
This algorithm is developed to discover shortest path from one node to other nodes in a
given graph. It can be used on directed graphs as well as undirected graphs.
Because it calculates the shortest path from a source node to all other nodes in the given
graph, this approach is also known as the single-source shortest path algorithm. This
algorithm produces the shortest path spanning tree.
The algorithm execution starts from source node. Graph G is the input to the algorithm.
Shortest path spanning tree is the output of this algorithm.
Dijkstra's Algorithm Steps:
Node P B E D A C
Distance 0 ∞ ∞ ∞ ∞ ∞
Let the source node P be visited. Add P to visited Vector. visited = {P}
Step 2:
The Node P has 3 adjacent nodes, B, A, C, with different distances. Hence The distance of S to
A, S to D and S to E will be changed in the distance vector.
P→B=6
P→A=8
P→C=7
Node P B E D A C
Distance 0 6 ∞ ∞ 8 7
Select a node from (Vertex[] – Visited[]) that has shortest distance. Add this node to
Visited. Find all the adjacent nodes to this node and perform relaxation for each of the
adjacent nodes. Update the distance vector accordingly.
The vertex having minimum distance among all the nodes in (Vertex[] – Visited[]) is B. Hence,
B is added to Visited. The adjacent node(s) to B is E. Hence perform Relaxation and update the
distance vector as follows.
Node P B E D A C
Distance 0 6 15 ∞ 8 7
Exercise: Perform repeat step and discover shortest paths to all the nodes from the source
node.
Requirements
1. Dijkstra's Algorithm is guaranteed to work properly if graphs have only positive weights.
The reason for this is that the edge weights are to be added to discover shortest path.
2. The algorithm may not perform properly if any negative weight exists in graph. The
movement a node is denoted as "visited", then the present path for that node can be
marked as a shortest path. Existence of negative weights may alter this path if sum of
weights gets reduced later.
25. Applications of Graph Data Structure:
Graph data structure has a variety of applications. Some of the most popular applications are:
Graphs have been used for representing flow of computation in programs of software
systems.
Google Maps has been using for constructing digital transportation systems. The
shortest path discovery between pair of vertices is being used by the Google.
Linkedin and Facebook have been using for social networks analysis.
Operating Systems use a Resource Allocation Graph where every process and
resource acts as a node. While we draw edges from resources to the allocated process.
Used in the world wide web where the web pages represent the nodes.
Blockchains also use graphs. The nodes store many transactions while the edges
connect subsequent blocks.
Used in modelling data.
Some other applications of graphs include:
o Knowledge graphs
o Biological networks
o Neural networks
o Product recommendation graphs
These are some of the fundamental terms and concepts used to describe and work with graphs in
the field of data structures and algorithms. Graphs are incredibly versatile and find applications
in various domains, including computer networks, social networks, recommendation systems,
and route planning, among others.