Graphs
Graphs
UNIT: Graphs
Course Name: Data Structure
Course Code: MA-223
• Non-linear data structures can also be more flexible than linear data structures.
For example, a binary search tree can be used to efficiently store and search for
elements in a sorted order, but it can also be modified to support other operations,
such as finding the maximum or minimum element, or finding the kth smallest
element.
• Non-linear data structures have several advantages over linear data structures.
They can represent complex relationships and dependencies between data
elements. They can also be more efficient for certain operations, such as
searching and inserting data.
DIFFERENCE
BETWEEN
LINEAR AND
NON-LINEAR
DATA
STRUCTURES
GRAPH rkweu7
A graph data structure is used to represent relations between pairs of objects .It consists of nodes (known as
vertices) that are connected through links (known as edges). The relationship between the nodes can be used to
model the relation between the objects in the graph.
GRAPH TERMINOLOGY
GRAPH TERMINOLOGY
1. VERTEX AND EDGES
Vertices are discrete points in a graph which are connected (or not) with help of edges. They are also called
nodes.
Edges are connection between a pair of nodes. They are also called arc.
GRAPH TERMINOLOGY
2. DIRECTED & UNDIRECTED GRAPHS
A directed graph is a set of vertices (nodes) connected by edges, with each node having a direction
associated with it.
In an undirected graph the edges are bidirectional, with no direction associated with them. Hence, the graph
can be traversed in either direction. The absence of an arrow tells us that the graph is undirected.’
GRAPH TERMINOLOGY
3. ADJACENT NODES
Two vertices are adjacent if they are endpoints of the same edge.
7. LENGTH OF PATH
It is defined as number of edges in a path.
GRAPH TERMINOLOGY
8. CYCLE
It is a path that starts and end at the same vertex.
TYPES OF GRAPHS
TYPES OF GRAPHS
There are many types of graphs as follows:
• Undirected Graph
• Directed Graph
• Weighted graph
• Complete graph
• Bipartite Graph
TYPES OF GRAPHS
1. UNDIRECTED GRAPH
A graph in which edges have no direction, i.e., the edges do not have arrows indicating the direction of
traversal.
TYPES OF GRAPHS
2. DIRECTED GRAPH
A graph in which edges have a direction, i.e., the edges have arrows indicating the direction of traversal.
TYPES OF GRAPHS
3. WEIGHTED GRAPH
A graph in which edges have weights or costs associated with them.
TYPES OF GRAPHS
4. COMPLETE GRAPH
A graph in which each vertex is connected to every other vertex.
TYPES OF GRAPHS
5. BIPARTITE GRAPH
A graph in which the vertices can be divided into two disjoint sets such that every edge connects a vertex
in one set to a vertex in the other set.
GRAPH
REPRESENTATION
GRAPH REPRESENTATION
There are generally two methods to represent graphs:
1. Adjacency Matrix
2. Adjacency List
GRAPH REPRESENTATION
1. ADJACENCY MATRIX
• Adjacency matrix is a sequential representation.
• It is used to represent which nodes are adjacent to each other. i.e. is there any edge connecting nodes
to a graph.
• In this representation, we have to construct a nXn matrix A. If there is any edge from a vertex i to vertex
j, then the corresponding element of A, ai,j = 1, otherwise ai,j= 0.
GRAPH REPRESENTATION
Example 1:
GRAPH REPRESENTATION
Example 2:
GRAPH REPRESENTATION
Example 3:
GRAPH REPRESENTATION
2. ADJACENCY LIST
• An adjacency list represents a graph as an array of linked lists. The index of the array represents a
vertex and each element in its linked list represents the other vertices that form an edge with the vertex.
GRAPH REPRESENTATION
Example 1:
GRAPH REPRESENTATION
Example 2:
GRAPH REPRESENTATION
Example 3:
GRAPH REPRESENTATION
CODE
GRAPH REPRESENTATION CODE
#include<iostream>
#include<unordered_map>
#include<vector>
class graph{
public:
unordered_map<int , vector<int>> adj;
};
GRAPH REPRESENTATION CODE
int main(){
cout<<"Enter number of nodes:"; //Number of Nodes
int n;
cin>>n;
graph g;
1. BFS
• Breadth-first search (BFS) traversal is a technique for visiting all nodes in a given network.
• This traversal algorithm selects a node and visits all nearby nodes in order.
• After checking all nearby vertices, examine another set of vertices, then recheck adjacent vertices.
• This algorithm uses a queue as a data structure as an additional data structure to store nodes for further
processing.
STEP 2:
Start from node 1 and put it in traversal array.
1
BFS
STEP 3:
Pop 1 from traversal queue and put in answer array.
Push neighbour of 1 in traversal queue.
1 2 3
STEP 4:
Pop 2 from traversal queue and put in answer queue and put
neighbour of 2 in traversal queue which are not visited.
1 2 3 4
1 2
BFS
STEP 5:
Pop 3 from traversal queue and put in answer array.
Push neighbour of 3 in traversal queue which are not visited.
1 2 3 4 5 6
1 2 3
STEP 6:
Pop 4 from traversal queue and put in answer array.
Push neighbour of 4 in traversal queue which are not visited.
1 2 3 4 5 6
1 2 3 4
BFS
STEP 7:
Pop 5 from traversal queue and put in answer array.
Push neighbour of 5 in traversal queue which are not visited.
1 2 3 4 5 6
1 2 3 4 5
STEP 8:
Pop 6 from traversal queue and put in answer array.
Push neighbour of 6 in traversal queue which are not visited.
1 2 3 4 5 6
1 2 3 4 5 6
GRAPH TRAVERSAL METHODS
CODE TO IMPLEMENT BSF
vector<int> BSF (int n, unordered_map<int , vector<int>> adj){
//input of no. of vertices and adjacency list
queue <int> q; //Making queue for visited elements.
q.push(0); //Pushing first element
int vis[n]={0}; //array to check visited element
vis[0]=1;
while(!q.empty()){
int node = q.front();
q.pop();
bsf.push_back(node);
• Step 2: Pop the top item from the stack and add it to the visited list.
• Step 3: Find all the adjacent nodes of the node marked visited and add the ones that are not yet visited, to
the stack.
STEP 2:
Start from node 1 and put it in traversal stack.
1
DFS
STEP 3:
Pop 1 from traversal stack and put in answer array.
Push neighbour of 1 in traversal stack.
1 2 3
STEP 4:
Pop 3 from traversal stack and put in answer queue and put
neighbour of 3 in traversal stack which are not visited.
1 2 3 4 6 5
1 3
BFS
STEP 5:
Pop 5 from traversal stack and put in answer array.
Push neighbour of 5 in traversal stack which are not visited.
1 2 3 4 6 5
1 3 5
STEP 6:
Pop 6 from traversal stack and put in answer array.
Push neighbour of 6 in traversal stack which are not visited.
1 2 3 4 6 5
1 3 5 6
BFS
STEP 7:
Pop 4 from traversal stack and put in answer array.
Push neighbour of 4 in traversal stack which are not visited.
1 2 3 4 6 5
1 3 5 6 4
STEP 8:
Pop 2 from traversal stack and put in answer array.
Push neighbour of 2 in traversal stack which are not visited.
1 2 3 4 5 6
1 3 5 6 4 2
GRAPH TRAVERSAL METHODS
Let's see how the Depth First Search algorithm works with an example. We use an undirected graph with 5
vertices.
We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its adjacent vertices in
the stack.
Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already been visited,
we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the Depth
First Traversal of the graph.
CODE TO IMPLEMENT DSF
vector<int> DSF (int n, unordered_map<int , vector<int>> adj){
//input of no. of vertices and adjacency list
stack <int> q; //Making stack for visited elements.
q.push(0); //Pushing first element
int vis[n]={0}; //array to check visited element
vis[0]=1;
while(!q.empty()){
int node = q.top();
q.pop();
dsf.push_back(node);
• A spanning tree is minimally connected, so removing one edge from the tree will make the graph
disconnected.
• A spanning tree is maximally acyclic, so adding one edge to the tree will create a loop.
• There can be a maximum nn-2 number of spanning trees that can be created from a complete graph.
• A spanning tree has n-1 edges, where 'n' is the number of nodes
MINIMUM SPANNING TREE
A minimum spanning tree can be defined as the spanning tree in which the sum of the weights of the edge is
minimum. The weight of the spanning tree is the sum of the weights given to the edges of the spanning tree.
MINIMUM SPANNING TREE
ALGORITHM
There are two algorithms to find MST(Minimum Spanning Tree)
• Kruskal’s Algorithm
• Prim’s Algorithm
1. Kruskal’s Algorithm
The steps for implementing Kruskal's algorithm are as follows:
STEP 1: As there is no self-loop and parallel edges so we arrange edges according to weight.
EDGES WEIGHT
8-7 1
7-6 2
3-9 2
1-2 4
3-6 4
7-9 6
3-4 7
8-9 7
1-8 8
2-3 8
4-5 9
5-6 10
2-8 11
4-6 14
STEP 2: Join 8 to 7
2 3 4
1 9 5
8 7 6
STEP 3: Join 6 to 7
2 3 4
1 9 5
8 7 6
STEP 4: Join 3 to 9
2 3 4
1 9 5
8 7 6
STEP 5: Join 1 to 2
2 3 4
1 9 5
8 7 6
STEP 6: Join 3 to 6
2 3 4
1 9 5
8 7 6
STEP 7: We don’t join 7 and 9 as it forms a loop. Join 3 and 4.
2 3 4
1 9 5
8 7 6
STEP 8: We don’t join 8 and 9 as it forms a loop. Join 1 and 8.
2 3 4
1 9 5
8 7 6
STEP 9: Join 4 and 5.
2 3 4
1 9 5
8 7 6
MINIMUM SPANNING TREE
2. Prim’s Algorithm
The steps for implementing Prim's algorithm are as follows:
3. Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree.
STEP 1: As there is no self-loop and parallel edges so we arrange edges according to weight.
STEP 2: We can select any node. For e.g. 9. Now we draw edge emerging from 9 which as minimum
weight. Join 3 and 9.
2 3 4
1 9 5
8 7 6
STEP 3: Now, we select edge emerging from 3 or 9 which has minimum weight . Join 3 and 6.
2 3 4
1 9 5
8 7 6
STEP 4: Now, we select edge emerging from 3 or 6 or 9 which has minimum weight . Join 7 and 6.
2 3 4
1 9 5
8 7 6
STEP 5: Now, we select edge emerging from 3 or 6 or 9 or 7 which has minimum weight . Join 7 and 8.
2 3 4
1 9 5
8 7 6
STEP 6: Now, we select edge emerging from 3 or 6 or 9 or 7 or 8 which has minimum weight . Join 3 and
4.
2 3 4
1 9 5
8 7 6
STEP 7: Now, we select edge emerging from 3 or 6 or 9 or 7 or 8 or 4 or 1 which has minimum weight .
Join 1 and 2.
2 3 4
1 9 5
8 7 6
STEP 8: Now, we select edge emerging from 3 or 6 or 9 or 7 or 8 or 4 which has minimum weight . Join 1
and 8.
2 3 4
1 9 5
8 7 6
STEP 9: Now, we select edge emerging from 3 or 6 or 9 or 7 or 8 or 4 or 1 which has minimum weight .
Join 4 and 5.
2 3 4
1 9 5
8 7 6
SHORTEST PATH IN
GRAPH
SHORTEST PATH IN GRAPH
As we know there are various types of graphs (weighted, unweighted, negative, cyclic, etc.) therefore having a
single algorithm that handles all of them efficiently is not possible. In order to tackle different problems, we have
different shortest-path algorithms, which can be categorised into two categories:
2. Set the non-visited node with the smallest current distance as the current node.
3. For each neighbor, N of the current node adds the current distance of the adjacent node with the weight of the
edge connecting 0->1. If it is smaller than the current distance of Node, set it as the new current distance of N.
Selected a b c d e z
Node
a 0 5 4
c 5 4 12 14
b 5 10 14
d 10 12 16
e 12 16
z 16
Distance from d to:
a = 10 (d -> b -> a)
b=5 (d -> b)
c=6 (d -> b -> c)
d=0
e=2 (d -> e)
z=6 (d-> z)
Selected a b c d e z
Node
d 5 8 0 2 6
e 5 8 2 6
b 10 5 6 6
c 10 6 6
z 10 6
a 10
FLOYD-WARSHALL ALGORITHM
Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all the pairs of vertices in a weighted
graph. This algorithm works for both the directed and undirected weighted graphs.
• Initialize the solution matrix same as the input graph matrix as a first step.
• Then update the solution matrix by considering all vertices as an intermediate vertex.
• The idea is to pick all vertices one by one and updates all shortest paths which include the picked vertex as an
intermediate vertex in the shortest path.
• When we pick vertex number k as an intermediate vertex, we already have considered vertices {0, 1, 2, .. k-
1} as intermediate vertices.
• For every pair (i, j) of the source and destination vertices respectively, there are two possible cases.
• k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it is.
• k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as dist[i][k] +
dist[k][j], if dist[i][j] > dist[i][k] + dist[k][j]
FLOYD-WARSHALL ALGORITHM
Example : Find Shortest path from every node to all other nodes using Floyd-Warshall Algorithm .
STEP 1: Creating 𝐴0
STEP 2: Creating 𝐴1
STEP 3: Creating 𝐴2
STEP 4: Creating 𝐴3
STEP 5: Creating 𝐴4
For example, The below graph has two strongly connected components {1,2,3,4} and {5,6,7} since there is path
from each vertex to every other vertex in the same strongly connected component.
GRAPH MATCHING
Graph matching in terms of data structures and algorithms (DSA) refers to the process of finding a correspondence
between the vertices of two graphs.
For Example:
Bipartite Graph Matching: Given a bipartite graph, find a matching that covers as many vertices as possible.