0% found this document useful (0 votes)
13 views

Graphs

The document provides an overview of data structures, specifically focusing on linear and non-linear data structures, with detailed sections on graphs. It explains graph terminology, types of graphs, graph representation methods, and traversal techniques such as BFS and DFS. Additionally, it discusses spanning trees and minimum spanning trees, including algorithms like Kruskal's and Prim's for finding the minimum spanning tree.

Uploaded by

22bee102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Graphs

The document provides an overview of data structures, specifically focusing on linear and non-linear data structures, with detailed sections on graphs. It explains graph terminology, types of graphs, graph representation methods, and traversal techniques such as BFS and DFS. Additionally, it discusses spanning trees and minimum spanning trees, including algorithms like Kruskal's and Prim's for finding the minimum spanning tree.

Uploaded by

22bee102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

NATIONAL INSTITUTE OF TECHNOLOGY, HAMIRPUR

Mathematics and Scientific Computing

UNIT: Graphs
Course Name: Data Structure
Course Code: MA-223

By: Mr. Keshav Kaundal


Linear Data Structurers:
• A linear data structure is a type of data structure that stores the data linearly
or sequentially.
• In the linear data structure, data is arranged in such a way that one element
is adjacent to its previous and the next element.
• It includes the data at a single level such that we can traverse all data into a
single run.

Types of Linear Data Structurers:


There are mainly four types of Linear Data Structures as follows:
1. Arrays
2. Linked List
3. Stacks
4. Queues
Non-Linear Data Structurers:
• A non-linear data structure is another important type in which data elements
are not arranged sequentially; mainly, data elements are arranged in random
order without forming a linear structure.
• Data elements are present at the multilevel, for example, tree.
• In trees, the data elements are arranged in the hierarchical form, whereas in
graphs, the data elements are arranged in random order, using the edges
and vertex.
Types of Non-Linear Data Structurers:
There are mainly two types of Linear Data Structures as follows:
1. Trees
2. Graphs
NEED OF NON-LINEAR DATA STRUCTURES
• One advantage of non-linear data structures is that they can provide faster and
more efficient access to data than linear data structures.

• 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.

Example: Nodes 1 and 2 are adjacent nodes.


GRAPH TERMINOLOGY
4. INCIDENT EDGE
An edge is incident on a vertex if the vertex is an endpoint of the edge.

Example: Edge E2 is incident on node A and C.


GRAPH TERMINOLOGY
5. DEGREE
Degree of a node is defined as a number of incident edges on a node.
GRAPH TERMINOLOGY
6. PATH
A path is a sequence of vertices such that each vertex is adjacent to the next. In a path, each edge can be
traveled only once.

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>

using namespace std;

class graph{
public:
unordered_map<int , vector<int>> adj;

void addEdge(int u, int v){


adj[u].push_back(v);
adj[v].push_back(u);
}

};
GRAPH REPRESENTATION CODE
int main(){
cout<<"Enter number of nodes:"; //Number of Nodes
int n;
cin>>n;

cout<<"Enter number of edges :"; //Number of Edges.


int e;
cin>>e;

graph g;

for(int i =0; i<e;i++){


cout<<"Enter Edge "<<i+1<<" :";
int u,v;
cin>>u>>v;
g.addEdge(u,v);
}
}
CODE TO PRINT GRAPH
void printAdjList(){
for(auto i: adj){
cout<<i.first<<"->";
for(auto j: i.second){
cout<<j<<",";
}
cout<<endl;
}
}
GRAPH TRAVERSAL
METHODS
GRAPH TRAVERSAL METHODS
We can traverse a graph in two ways :
1. BFS ( Breadth First Search )
2. DFS ( Depth First Search )

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.

• Queue size is the maximum total number of vertices in the graph.


BFS
STEP 1:
Create two arrays -> traversal and answer

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;

vector<int> bsf; //Final BSF order

while(!q.empty()){
int node = q.front();
q.pop();
bsf.push_back(node);

for(auto i: adj[node]){ //Traversing on vector of popped key.


if(!vis[i]){
q.push(i);
vis[i]=1;
}
}
}
return bsf;
}
GRAPH TRAVERSAL METHODS
2. DFS
• Step 1: Insert the root node or starting node of a tree or a graph in the stack.

• 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 4: Repeat steps 2 and 3 until the stack is empty.


DFS
STEP 1:
Create one traversal stack and one answer array.

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;

vector<int> dsf; //Final DSF order

while(!q.empty()){
int node = q.top();
q.pop();
dsf.push_back(node);

for(auto i: adj[node]){ //Traversing on vector of popped key.


if(!vis[i]){
q.push(i);
vis[i]=1;
}
}
}
return dsf;
}
SPANNING TREE
SPANNING TREE
A spanning tree can be defined as the subgraph of an undirected connected graph. It includes all the vertices
along with the least possible number of edges.
If any vertex is missed, it is not a spanning tree.
A spanning tree is a subset of the graph that does not have cycles, and it also cannot be disconnected.
SPANNING TREE
PROPERTIES
• There can be more than one spanning tree of a connected graph G.

• A spanning tree does not have any cycles or loop.

• 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:

1. Remove all Self-loops and parallel edges.


2. In removing parallel edges remove edge with high weight.
3. Sort all the edges from low weight to high.
4. Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle,
then reject this edge.
5. Keep adding edges until we reach all vertices.
MINIMUM SPANNING TREE
Example : Find MST using Kruskal’s Algorithm

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:

1. Remove all Self-loops and parallel edges.

2. Initialize the minimum spanning tree with a vertex chosen at random.

3. Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree.

4. Keep repeating step 2 until we get a minimum spanning tree.


MINIMUM SPANNING TREE
Example : Find MST using Prim’s Algorithm

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:

1. Single Source Shortest Path Algorithms


2. All Pair Shortest Path Algorithms

1. Single Source Shortest Path Algorithms


In this algorithm we determine the shortest path of all the nodes in the graph with respect to a single node i.e.
we have only one source node in this algorithms.

Algorithm used here is Dijkstra’s Algorithm

2. All Pair Shortest Path Algorithms


Contrary to the single source shortest path algorithm, in this algorithm we determine the shortest path between
every possible pair of nodes.

Algorithm used here is Floyd-Warshall Algorithm


DIJKSTRA’S ALGORITHM
1. Mark the source node with a current distance of 0 and the rest with infinity.

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.

4. Mark the current node 1 as visited.

5. Go to step 2 if there are any nodes are unvisited.


DIJKSTRA’S ALGORITHM
Example : Find Shortest path from node a to all other nodes (same for node d) using Dijkstra’s Algorithm .
Distance from a to:
a=0
b = 5 (a -> b)
c = 4 (a -> c)
d = 10 (a -> b ->d)
e = 12 (a -> b -> d -> e)
z = 16 (a-> b -> d -> z)

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

Distance from 1 to 1 : 0 Distance from 4 to 1 : 5


Distance from 1 to 2 : 3 Distance from 4 to 2 : 3
Distance from 1 to 3 : 7 Distance from 4 to 3 : 2
Distance from 1 to 4 : 5 Distance from 4 to 4 : 0
Distance from 2 to 1 : 2
Distance from 2 to 2 : 0
Distance from 2 to 3 : 6
Distance from 2 to 4 : 4
Distance from 3 to 1 : 3
Distance from 3 to 2 : 1
Distance from 3 to 3 : 0
Distance from 3 to 4 : 5
DIRECTED ACYCLIC GRAPHS
A directed acyclic graph is a directed graph that has no cycles.
ARTICULATION POINTS
A vertex is said to be an articulation point in a graph if removal of the vertex and associated edges disconnects
the graph.
BICONNECTED COMPONENTS
A biconnected component of a graph is a connected subgraph that cannot be broken into disconnected pieces
by deleting any single node (and its incident links). An articulation point is a node of a graph whose removal
would cause an increase in the number of connected components.
STRONG COMPONENTS
A strongly connected component is the component of a directed graph that has a path from every vertex to every
other vertex in that component. It can only be used in a directed graph.

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.

You might also like