0% found this document useful (0 votes)
34 views44 pages

08 Graphs

This document provides an overview of graphs as a non-linear data structure consisting of vertices and edges, along with their applications and various types such as directed, undirected, weighted, and bipartite graphs. It also covers key concepts like adjacency, degree of vertices, paths, cycles, and operations for graph representation including edge lists, adjacency matrices, and adjacency lists. Additionally, it discusses graph traversal methods and their importance in exploring graph structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views44 pages

08 Graphs

This document provides an overview of graphs as a non-linear data structure consisting of vertices and edges, along with their applications and various types such as directed, undirected, weighted, and bipartite graphs. It also covers key concepts like adjacency, degree of vertices, paths, cycles, and operations for graph representation including edge lists, adjacency matrices, and adjacency lists. Additionally, it discusses graph traversal methods and their importance in exploring graph structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Data Structures and Algorithms - EE 390

Module 8
Graphs

Dr. Anirban Dasgupta


Assistant Professor

Department of Electronics And Electrical Engineering, IIT Guwahati


Graph Data Structure
Graph is a non-linear data structure
consisting of vertices and edges.

The edges are lines or arcs that connect any


two nodes in the graph.

Graph consists of a finite set of vertices and


In the above Graph,
set of edges which connect a pair of nodes.
the set of vertices
V = {0,1,2,3,4}
the set of edges
Graphs are used to represent networks. E = {01, 12, 23, 34, 04, 14, 13}

Department of Electronics And Electrical Engineering, IIT Guwahati


Graphs - Applications

Paths in a city Circuit network Social networks like


LinkedIn, Facebook

Brain networks DNA structure of an Markov models


organism

Department of Electronics And Electrical Engineering, IIT Guwahati


Graphs - Terminology
• A vertex ‘v’ is said to be adjacent vertex of vertex ‘u’ if and only if there
Adjacent Vertex exists an edge between ‘u’ and ‘v’.
• Number of vertices incident on a vertex in an undirected graph
Degree of a Vertex • In case of directed graph, Degree is defined as Indegree and Outdegree
• A path of length ‘n’ from vertex ‘u’ to node ‘v’ is defined as sequence of
Path n+1 vertices.
• A cycle is a path that starts and ends at the same vertex, forming a closed
Cycle loop.

Isolated Vertex • A node with degree 0 is known as isolated vertex.

Pendent Vertex • vertex with degree one is called a pendent vertex.

Forest • A forest is a disjoint set of trees or a collection of disjoint acyclic graphs.

Department of Electronics And Electrical Engineering, IIT Guwahati


Graphs - Types
Graphs

4
1 Connected Disconnected 1
4

A connected graph has a path between 5


2 3
2 3 every pair of nodes, while a
Disconnected
Connected disconnected graph has at least two
nodes without a connecting path.

Department of Electronics And Electrical Engineering, IIT Guwahati


Graphs - Types
Graphs

Directed Undirected Mixed


1
1 1

2 3
2 3 2 3
Directed Undirected Mixed
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
Graphs

Weighted Unweighted

1 1

3 5

8
2 3 2 3

Weighted Undirected

Department of Electronics And Electrical Engineering, IIT Guwahati


Graphs - Types
1 1

2 3 2 3

Unweighted Unweighted
Directed Undirected

1 1

3 5 3
5

8 8
2 3 2 3
4 Weighted
Weighted Undirected
Directed
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
5 6 Graphs 1
4

4 1 Sparse Dense 5
2 3

Dense
Complete
1
2 3 • Sparse graphs have relatively fewer edges 4
compared to the maximum possible edges. 5
Sparse
• Dense graphs have a large number of
edges, often close to the maximum
"sparsity" of a graph refers 2
possible.
to how many edges it has 3
relative to the maximum
• In a complete graph, every pair of distinct
Complete
possible number of edges nodes is connected by an edge.
between its vertices Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
Graphs

1 Cyclic Acyclic 1

•A cyclic graph contains at least one cycle (a


closed path of edges), while an acyclic graph 2 3
2 3
has no cycles. Acyclic
Cyclic •Directed acyclic graphs (DAGs) are
particularly important in various
applications.
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
Tree is a Special Case of Acyclic Graph
Graphs
1 1
Parent
Cyclic Acyclic

Tree 2 3 2 3
Acyclic Tree

Department of Electronics And Electrical Engineering, IIT Guwahati


Graphs - Types
• An Eulerian graph is a graph containing an Eulerian cycle
and an Eulerian path.
• Eulerian Path is a path in a graph that visits every edge
Graphs exactly once.
• Eulerian Cycles (Circuits) are cycles that where you start
from a vertex and reach the same vertex by traversing every
Cyclic Acyclic edge of the graph exactly once.

1 5
Eulerian Tree
2 3 6

Eulerian Graph is a Special Case 4 7


of Cyclic Graph Eulerian
Cycles
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
A Hamiltonian graph G having N vertices and E edges is a connected graph
that has a Hamiltonian cycle in it where a Hamiltonian cycle is a closed path
that visits each vertex of graph G exactly once.
Graphs A Hamiltonian circuit (cycle) visits each vertex in a graph exactly once but
may repeat or miss edges, whereas an Eulerian circuit traverses every edge
Cyclic Acyclic in a graph exactly once but may repeat vertices.

Eulerian Tree 2
1
Hamiltonian 1
4
Both 2 3
3
7 5 4
Hamiltonian Graph is a Special 6
Case of Cyclic Graph Hamiltonian but not Eulerian
Eulerian but not Hamiltonian
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
Graphs
5 6

4 1
Bipartite Non-bipartite 1
4

• In a bipartite graph, nodes can be 5


partitioned into two sets such that all 2 3
2 3
edges connect nodes from different sets.
Bipartite • This property is often used in modeling Non-bipartite
relationships between two distinct classes
of objects.
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Types
Graphs
• A complete bipartite graph or biclique is a
5 6 special kind of bipartite graph where
every vertex of the first set is connected to Non-
Bipartite
every vertex of the second set bipartite
• All complete bipartite graphs which are
4 1 trees are stars
Complete /
Biclique

2 3 Star
Complete
Bipartite
Graph

Department of Electronics And Electrical Engineering, IIT Guwahati


Clique In Graphs
A clique is a subset of vertices in a graph such that every two vertices in
the subset are adjacent, forming a complete subgraph.
Properties:
• Complete Subgraph: A clique is a subgraph where all vertices are
connected to each other.
• Degree: In a clique of size 𝑘, each vertex has a degree of 𝑘−1
because it is connected to all other vertices in the clique.
• Size: A clique is identified by its size 𝑘, which is the number of
vertices it contains.

Department of Electronics And Electrical Engineering, IIT Guwahati


Distance between Two Vertices
• Number of edges in a shortest path between two vertices in unweighted graphs.
• For weighted graphs, it is the sum of weights for a shortest path.
• If there are multiple paths connecting two vertices, then the shortest path is
considered as the distance between the two vertices.
5 6

Distance from 3-1 is 2


Distance from 3-6 is 3
4 1
Distance from 5-1 is 2

2 3

Department of Electronics And Electrical Engineering, IIT Guwahati


Eccentricity of a Vertex
The maximum distance between a vertex to all other vertices is
considered as the eccentricity of vertex.

a b from ‘a’ to ‘b’ is 1 (‘ab’),


from ‘a’ to ‘c’ is 1 (‘ac’),
from ‘a’ to ‘d’ is 1 (‘ad’),
from ‘a’ to ‘e’ is 2 (‘ab’-‘be’) or (‘ad’-‘de’),
c d e
from ‘a’ to ‘f’ is 2 (‘ac’-‘cf’) or (‘ad’-‘df’),
from ‘a’ to ‘g’ is 3 (‘ac’-‘cf’-‘fg’) or (‘ad’-‘df’-‘fg’).
f g
So the eccentricity of ‘a’ is 3, which is the distance from vertex
‘a’ to ‘g’, as it is the maximum of all distances from ‘a’

Department of Electronics And Electrical Engineering, IIT Guwahati


Radius of a Connected Graph
The minimum eccentricity from all the vertices is considered as the
radius of the Graph G.

a b e(a) = 3
e(b) = 3
e(c) = 3
e(d) = 2
c d e
e(e) = 3
e(f) = 3
f g e(g) = 3
So the minimum eccentricity of the graph is 2, which is for the
vertex ‘d’, hence, is the radius

Department of Electronics And Electrical Engineering, IIT Guwahati


Diameter of a Connected Graph
The maximum eccentricity from all the vertices is considered as the
diameter of the Graph G.

a b e(a) = 3
e(b) = 3
e(c) = 3
e(d) = 2
c d e
e(e) = 3
e(f) = 3
f g e(g) = 3
So the maximum eccentricity of the graph is 3, which is the
diameter of the graph

Department of Electronics And Electrical Engineering, IIT Guwahati


Central Point of a Connected Graph
If the eccentricity of a vertex is equal to its radius, then that vertex is
known as the central point of the graph.

a b e(a) = 3
e(b) = 3
e(c) = 3
e(d) = 2
c d e
e(e) = 3
e(f) = 3
f g e(g) = 3
So the ‘d’ is the only central point of the graph

The set of all central points of ‘G’ is called the centre of the Graph.

Department of Electronics And Electrical Engineering, IIT Guwahati


Circumference of a Connected Graph
The number of edges in the longest cycle of ‘G’ is called as the
circumference of ‘G’.

a b
the circumference is 6, which we derived
from the longest cycle
• a-c-f-g-e-b-a
c d e
• a-c-f-d-e-b-a
f g
The length of the shortest cycle and the circumference
of an acyclic graph is defined to be infinity.
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Transpose
Transpose of a directed graph G is another directed graph H on the same set of vertices
with all of the edges reversed compared to the orientation of the corresponding edges in G.

If G contains an edge (u, v) then the transpose of G contains an edge (v, u) and vice versa.

a b a b

c d e c d e

f g f g

Department of Electronics And Electrical Engineering, IIT Guwahati


Graph Representation

Representations

Adjacency Adjacency
Edge List
Matrix List

Department of Electronics And Electrical Engineering, IIT Guwahati


Edge List Representation
• Stores each edge of the
graph as a tuple or a
structure containing
information about the
vertices it connects
• Format is (source vertex,
destination vertex)
(0, 1), (0,4), (1,2), (1,3), (1,4), (2,3), (3,4)
• Well-suited for sparse
graphs
O(V2)
Department of Electronics And Electrical Engineering, IIT Guwahati
Adjacency Matrix Representation
• Adjacency Matrix is a 2D array of size V × V,
where V is the number of vertices in a graph.
• Let the 2D array be adj[][], a slot adj[i][j] = 1
indicates that there is an edge from vertex i to
vertex j.
• Adjacency matrix for undirected graph is
always symmetric.
• Adjacency Matrix is also used to represent
weighted graphs.
• If adj[i][j] = w, then there is an edge from
vertex i to vertex j with weight w. O(V2)

Department of Electronics And Electrical Engineering, IIT Guwahati


Adjacency List Representation
• An array of lists is used.
• The size of the array is equal to
the number of vertices.
• Let the array be an array[].
• An entry array[i] represents the
list of vertices adjacent to the ith
vertex.
• This representation can also be
used to represent a weighted
graph. The weights of edges can
be represented as lists of pairs.
O(V+E)
Department of Electronics And Electrical Engineering, IIT Guwahati
Graphs - Operations
Operation Adjacency list Adjacency matrix
Add vertex O(V+E) O(V2)
Add edge O(1) O(1)
Remove vertex O(V+E) O(V2)
Remove edge O(1) O(1)
Query O(V) O(1)

Graph has V vertices and Slow to add or remove


Slow in query
E edges vertices, because matrix must
be resized/copied

Department of Electronics And Electrical Engineering, IIT Guwahati


Graph Algorithms

Department of Electronics And Electrical Engineering, IIT Guwahati


Graph Traversal
• process of visiting each vertex in a graph
• graph traversal may require that some vertices be visited more than
once, since it is not necessarily known before transitioning to a vertex
that it has already been explored
• as graphs become denser, this redundancy becomes more prevalent,
causing computation time to increase
• it is usually necessary to remember which vertices have already been
explored by the algorithm, so that vertices are revisited as infrequently
as possible

Department of Electronics And Electrical Engineering, IIT Guwahati


Graph Traversal: Visit and Explore

• Visiting is limited to a single node


only where as exploring is to visit all
it’s connecting nodes
• Visit : When a node is read but have
at-least one unread adjacent node
• Explore : When a node is read but all Yellow : Visited ( 1 and 6 both have unvisited connections)
its connecting nodes are also read Green: Explored ( 2,4,5 do not have any unvisited
connections)
White : Not visited, Not Explored

Department of Electronics And Electrical Engineering, IIT Guwahati


Graph Traversal Methods

Traversal
Algorithms

Breadth First Depth First


Search (BFS) Search (DFS)

used to visit all of the nodes of a given graph

Department of Electronics And Electrical Engineering, IIT Guwahati


Breadth First Search (BFS)
bfs(vertices, start)
Input: The list of vertices, and the start vertex.
• In this traversal algorithm one node Output: Traverse all of the nodes, if the graph
is connected.
is selected and then all of the Begin
adjacent nodes are visited one by define an empty queue q
at first mark all nodes status as unvisited
one add the start vertex into the q
while que is not empty, do
• After completing all of the adjacent delete item from q and set to u
display the vertex u
vertices, it moves further to check for all vertices i adjacent with u, do
another vertices and checks its if vertices[i] is unvisited, then
mark vertices[i] as temporarily visited
adjacent vertices again add v into the queue
mark
• Queue implementation done
mark u as completely visited
done
End
Department of Electronics And Electrical Engineering, IIT Guwahati
BFS Illustration

Department of Electronics And Electrical Engineering, IIT Guwahati


Depth First Search (DFS)
dfs(vertices, start)
Input: The list of all vertices, and the start
node.
Output: Traverse all nodes in the graph.
Begin
initially make the state to unvisited for all
• One starting vertex is given nodes
push start into the stack
• When an adjacent vertex is found, while stack is not empty, do
it moves to that adjacent vertex pop element from stack and set to u
display the node u
first and try to traverse in the same if u is not visited, then
mark u as visited
manner for all nodes i connected to u, do
if ith vertex is unvisited, then
• Stack implementation push ith vertex into the stack
mark ith vertex as visited
done
done
End
Department of Electronics And Electrical Engineering, IIT Guwahati
DFS Illustration

Department of Electronics And Electrical Engineering, IIT Guwahati


Complexity: BFS and DFS

• Both Breadth-First Search (BFS) and Depth-First Search (DFS)


for traversing graphs have a time complexity of O(V + E),
where V represents the number of vertices and E represents the
number of edges.
• The space complexity for DFS is O(h) where h is the maximum
height of the tree.
• The space complexity of Breadth-First Search (BFS) in a graph
is O(V)

Department of Electronics And Electrical Engineering, IIT Guwahati


Connected Components
• A connected component of an undirected graph is a subgraph in which every two vertices are
connected to each other by a path(s), and which is connected to no other vertices outside the subgraph.
• Given an undirected graph, the task is to print all the connected components line by line.

Do either BFS or DFS starting from every unvisited


vertex, and we get all strongly connected components.
Algorithm
•Initialize all vertices as not visited.
•Do the following for every vertex v:
• If v is not visited before, call the DFS. and print the
newline character to print each component in a new line
• Mark v as visited and print v.
Time Complexity: O(V + E) where V is the number
• For every adjacent u of v, If u is not visited, then
of vertices and E is the number of edges.
recursively call the DFS.
Auxiliary Space: O(V)
Department of Electronics And Electrical Engineering, IIT Guwahati
Number of Islands
• A group of connected 1s forms an island.
• Given a binary 2D matrix of size N×M, find the number of islands.

Department of Electronics And Electrical Engineering, IIT Guwahati


Number of Islands

Using DFS and Additional Matrix – O(N×M) time and O(N×M) space
• Initialize count = 0 and Boolean matrix, visited[][] to false.
• For each cell of the input matrix check if the value of the current cell
is 1 and is not visited , call for the DFS for all its 8 neighboring cells.
• If the neighbor is safe to visit and is not visited already Call DFS
recursively and Increment count by 1
• Return count as the final answer.

Department of Electronics And Electrical Engineering, IIT Guwahati


Flood Fill Algorithm
• Given a 2D matrix img[][] where
each value img[i][j] is an integer
representing the color of that
pixel also given a coordinate (sr,
sc) representing the starting pixel
(row and column) of the flood
fill, and a pixel value newColor.
• The “flood fill” task is to replace
the existing color of the given
pixel and all the adjacent same-
colored pixels with the given
newColor.

Department of Electronics And Electrical Engineering, IIT Guwahati


Flood Fill Algorithm

• Applications:
• Image Processing: Paint bucket tool in applications like Photoshop or MS Paint.
• Pathfinding: In game development or in simulations where regions need to be marked.
• Maze Solving: To explore or mark areas in mazes or grids.

Department of Electronics And Electrical Engineering, IIT Guwahati


Rotten Oranges
Given a matrix of dimension M×N,
where each cell in the matrix can have
values 0, 1 or 2 which has the following
meaning:
0: Empty cell
1: Cells have fresh oranges
2: Cells have rotten oranges
The task is to find the minimum time
required so that all the oranges become
rotten.
A rotten orange at index (i,j ) can rot
other fresh oranges which are its
neighbors (up, down, left, and right).
Department of Electronics And Electrical Engineering, IIT Guwahati
Rotten Oranges

Approach: BFS
• First, enqueue all rotten oranges with
the time set to 0 (since they are already
rotten).
• For each minute, rotten oranges spread
to adjacent fresh oranges, marking
them as rotten and updating their time.
• If any fresh orange cannot be reached
(i.e., no adjacent rotten orange can
spread to it), return -1.
• Time and space complexity O(N×M)

Department of Electronics And Electrical Engineering, IIT Guwahati

You might also like