Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

DATA STRUCTURES – ECE – II

YEAR / III SEM – 22CS301


BY
RAMYA R,

AP/COE,

1
UNIT – IV
Graph Definition – Representation of Graphs – Types of Graph -
Breadth-first traversal – Depth-first traversal –– Bi-connectivity –
Euler circuits – Topological Sort – Dijkstra's algorithm.

2
GRAPH

3
Definition
Graph G consists of two things:

1. A set V=V(G) whose elements are called vertices, points or nodes of G.


2. A set E = E(G) of an unordered pair of distinct vertices called edges of G.
3. We denote such a graph by G(V, E) vertices u and v are said to be adjacent if there is an edge
e ={u, v}.

4
Difference between Tree and Graph

Graph can have multiple path between two nodes

5
1.Finite Graph
A graph is said to be finite if it has a finite number of vertices and a finite number of edges. A
finite graph is a graph with a finite number of vertices and edges

6
2.InFinite Graph

A graph is said to be infinite if it has an infinite number of vertices as well as an infinite number
of edges.

7
3. Trivial Graph
A graph is said to be trivial if a finite graph contains only one vertex and no edge.
A trivial graph is a graph with only one vertex and no edges. It is also known as a
singleton graph or a single vertex graph.

4. Simple Graph
A simple graph is a graph that does not contain more than one edge
between the pair of vertices. A simple railway track connecting
different cities is an example of a simple graph.

8
5.Multi Graph
Any graph which contains some parallel edges but doesn’t contain any self-loop is called a
multigraph. For example a Road Map.

•Parallel Edges: If two vertices are connected with more than one edge then such edges are called
parallel edges that are many routes but one destination.

•Loop: An edge of a graph that starts from a vertex and ends at the same vertex is called a loop or a
self-loop.

9
6.Null Graph
▪ A graph of order n and size zero is a graph where there are only isolated vertices with no edges
connecting any pair of vertices.

▪ A null graph is a graph with no edges.

10
7.Complete Graph
❑ A simple graph with n vertices is called a complete graph if the degree of each vertex is n-1,
that is, one vertex is attached with n-1 edges or the rest of the vertices in the graph.

❑ A complete graph is also called Full Graph.

11
8. Pseudo Graph
❑ A graph G with a self-loop and some multiple edges is called a pseudo graph.

❑ A pseudograph is a type of graph that allows for the existence of loops (edges that connect a
vertex to itself) and multiple edges (more than one edge connecting two vertices).

12
9. Regular Graph
A simple graph is said to be regular if all vertices of graph G are of equal degree. All complete
graphs are regular but vice versa is not possible.

13
10.Weighted Graph
A Graph G=(V,E) is called a labelled or weighted graph because each edge has a value or
weight representing the cost of traversing that edge.

14
11. Directed Graph or Digraph
❑ A graph G = (V, E) with a mapping f such that every edge maps onto some ordered pair of vertices
(Vi, Vj) are called a Digraph.
❑ It is also called Directed Graph.
❑ The ordered pair (Vi, Vj) means an edge between Vi and Vj with an arrow directed from Vi to Vj.
Here in the figure: e1 = (V1, V2) e2 = (V2, V3) e4 = (V2, V4)

15
12. Connected Graph
If there is a path between one vertex of a graph data structure and any other vertex,
the graph is connected.

16
14.Disconnected Graph
When there is no edge linking the vertices, you refer to the null graph as a disconnected
graph.

17
15.Cyclic Graph

❑ If a graph contains atleast one graph cycle,it is considered to be cyclic.

❑ A graph G consisting of n vertices and n> = 3 that is V1, V2, V3- – – – Vn and
edges (V1, V2), (V2, V3), (V3, V4)- – – – (Vn, V1) are called cyclic graph.

18
15.Acyclic Graph

When there are no cycles in the graph, it is called as Acyclic Graph

19
16.SubGraph

The vertices and edges of a graph that are subsets of another graph are known
as a Subgraph.

20
Terminologies of Graphs in Data Structures

1. Vertex: A vertex represents each node of a graph. For example, in the above graph,
A, B, C, D, E are the vertices.

2. Edge: It is the path between two nodes/vertices.

3. Path: It is the sequence/order of vertices to reach from one node to another. For
example, suppose we wish to reach from node A to node E. the possible paths are:
A→C→E or A→B→C→E.

4. Closed path: If the initial and the final nodes are the same, then the path is a closed
path.

5. Simple path: A simple path is a path in which all the nodes are distinct.

21
Terminologies of Graphs in Data Structures

6. Adjacency: Two vertices are adjacent if there exists an edge that connects
those two vertices. For example, the nodes A-B, B-C, A-C, C-D, C-E are all
adjacent nodes.

7. Degree of a node: For each node in a graph, its degree is the number of edges
connected to that node.

8. Isolated node: A node having degree = 0. Thus, an isolated node is not


connected to any other node.

22
Representation of Graphs

1.Sequential or Adjacency matrix representation

2. Linked List or Adjacency list representation

23
Adjacency matrix representation for undirected Graph
➢ An adjacency matrix is a 2D array of V x V vertices.

➢ Each row and column represent a vertex.

➢ If the value of any element a[i][j] is 1, it represents that there is an edge connecting
vertex i and vertex j.

24
Adjacency matrix representation for undirected Graph
➢ The adjacency matrix for the graph is

Since it is an undirected graph, for edge (0,2), we also need to mark edge (2,0); making the
adjacency matrix symmetric about the diagonal.

25
Adjacency matrix representation for Unweighted
directed Graph
❑ In a directed graph, edges represent a specific path from one vertex to another vertex.

❑ Consider the below-directed graph and try to construct the adjacency matrix of it.

26
Adjacency matrix representation for Weighted directed
Graph
❑ It is similar to an adjacency matrix representation of a directed graph except that instead
of using the '1' for the existence of a path, here we have to use the weight associated with
the edge.
❑ The weights on the graph edges will be represented as the entries of the adjacency matrix.

27
#include <stdio.h> Adjacency matrix implementation
#define V 4
void printAdjMatrix(int arr[][V])
void graph(int arr[][V]) {
{ int i, j;
int i, j; for (i = 0; i < V; i++) {
for (i = 0; i < V; i++) printf("%d: ", i);
for (j = 0; j < V; j++) for (j = 0; j < V; j++) {
arr[i][j] = 0; printf("%d ", arr[i][j]);
} }
printf("\n");
void insertEdge(int arr[][V], int i, int j) }
{ }
arr[i][j] = 1; int main() {
arr[j][i] = 1; int adjMatrix[V][V];
} graph(adjMatrix);

28
Adjacency matrix implementation

insertEdge(adjMatrix, 0, 1);
insertEdge(adjMatrix, 0, 2);
insertEdge(adjMatrix, 1, 2); Output :
insertEdge(adjMatrix, 2, 0); 0: 0 1 1 0
insertEdge(adjMatrix, 2, 3); 1: 1 0 1 0
2: 1 1 0 1
3: 0 0 1 0
printAdjMatrix(adjMatrix);

return 0;
}

29
PROS AND CONS OF ADJACENCY MATRIX
✓Checking whether there is an edge from node i to node j very efficiently, and in constant
time usually.
✓For dense graphs, where the number of edges are very large, adjacency matrix are the best
choice[ faster]. If the graph is sparse, then most of the cells are vacant, hence wasting more
space.

x The most notable disadvantage that comes with Adjacency Matrix is the usage of V x
V space, where V is the number of vertices. In real life, we do not have so dense
connections ,where so many edges will be used.
x So, the space mostly gets wasted, and hence for sparse graphs with less number of edges
Adjacency Lists are always preferred.

30
Adjacency List Representation of Graphs
➢ 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.

31
Adjacency List implementation printf("\n How Many Vertices ? : ");
#include <stdio.h> scanf("%d", &n);
#define new_node (struct for ( i = 1 ; i <= n ; i++ )
node*)malloc(sizeof(struct node)) adj_list[i] = NULL;
struct node read_graph(adj_list, n);
{ int vertex; printf("\n Vertex \t Degree ");
struct node *next; for ( i = 1 ; i <= n ; i++ ) {
}; deg = 0; p = adj_list[i];
void main() while( p != NULL ) {
{ undir_graph(); deg++;
} p = p -> next; }
int undir_graph() printf("\n\n %5d \t\t %d\n\n", i, deg);
{ }
struct node *adj_list[10], *p; return;
int deg, i, j, n; }

32
int read_graph ( struct node *adj_list[10], int n ) Adjacency List implementation
{ { c = new_node;
c -> vertex = j;
int i, j;
c -> next = NULL;
char reply;
if ( adj_list[i] == NULL )
struct node *p, *c; adj_list[i] = c;
for ( i = 1 ; i <= n ; i++ ) { else
for ( j = 1 ; j <= n ; j++ ) { {
if ( i == j ) p = adj_list[i];
while ( p -> next != NULL )
continue;
p = p -> next;
printf("\n Vertices %d & %d are Adjacent ? (Y/N)
p -> next = c;
:", i, j);
}}
scanf("%c", &reply); } } return;
if ( reply == 'y' || reply == 'Y' ) }
33
PROS AND CONS OF ADJACENCY LIST
✓Since, we use list for storage, memory is managed effectively, adjacency lists are storage
efficient

x To find any particular node in an adjacency list, we need to explore all the connected
nodes. So, usually it is slower as compared to finding a node in an adjacency matrix.
x It is not a good option for dense graphs because, we will unnecessarily be storing so
many edges in the linked list and hence it will not be time efficient in terms of certain
operations(like search or peek).

34
To Do..
1. Construct a Adjacency list and matrix for the following graphs

35
Operations on Graphs
The operations you perform on the graphs in data structures are listed
below:

•Creating graphs
•Insert vertex
•Delete vertex
•Insert edge
•Delete edge

36
Creating Graphs
There are two techniques to make a graph:

1. Adjacency Matrix:

The adjacency matrix of a simple labeled graph, also known as the connection matrix, is a matrix with rows
and columns labeled by graph vertices and a 1 or 0 in position depending on whether they are adjacent or
not.

2. Adjacency List:

A finite graph is represented by an adjacency list, which is a collection of unordered lists. Each unordered
list describes the set of neighbors of a particular vertex in the graph within an adjacency list.

37
Insert Vertex on Graphs
When you add a vertex that after introducing one or more vertices or nodes, the graph's size grows by one,
increasing the matrix's size by one at the row and column levels.

38
Delete Vertex on Graphs
➢ Deleting a vertex refers to removing a specific node or vertex from a graph that has been saved.

➢ If a removed node appears in the graph, the matrix returns that node. If a deleted node does not appear in the
graph, the matrix returns the node not available.

39
Insert Edges on Graphs
➢ Connecting two provided vertices can be used to add an edge to a graph.

40
Delete Edge Operations on Graphs
The connection between the vertices or nodes can be removed to delete an edge.

41
To Do..
1. Construct a Adjacency list and matrix for the following graphs

42
Graph Traversal Algorithm
Traversal means the process of visiting every node in the graph

Breadth First Search : a graph traversal algorithm, where we start from a


selected(source) node and traverse the graph level by level, by exploring the neighbor
nodes at each level.

Depth First Search (DFS) is a graph traversal algorithm, where we start from a
selected(source) node and go into the depth of this node by recursively calling
the DFS function until no children are encountered.

When the dead-end is reached, this algorithm backtracks and starts visiting the other
children of the current node

43
Breadth First Search(BFS)
➢ The Breadth First Search (BFS) algorithm is used to search a graph data
structure for a node that meets a set of criteria.

➢ It starts at the root of the graph and visits all nodes at the current depth level
before moving on to the nodes at the next depth level.

➢ BFS uses queue data structure for traversal.

To avoid processing a node more than once, we divide the vertices into two
categories:

•Visited and
•Not visited.

44
Breadth First Search(BFS)

45
Algorithm
The algorithm works as follows:

1.Start by putting any one of the graph's vertices at the back of a queue.

2.Take the front item of the queue and add it to the visited list.

3.Create a list of that vertex's adjacent nodes. Add the ones which aren't
in the visited list to the back of the queue.

4.Keep repeating steps 2 and 3 until the queue is empty.

46
Breadth First Search
Let us understand the working of the algorithm with the help of the following example.
Step1: Initially queue and visited arrays are empty.

Queue and visited arrays are empty initially.

47
Breadth First Search
Step2: Push node 0 into queue and mark it visited.

Push node 0 into queue and mark it visited.

48
Breadth First Search
Step 3: Remove node 0 from the front of queue and visit the unvisited neighbours and push them
into queue.

Remove node 0 from the front of queue and visited the


unvisited neighbours and push into queue.

49
Breadth First Search
Step 4: Remove node 1 from the front of queue and visit the unvisited neighbours and push them
into queue.

Remove node 1 from the front of queue and visited the


unvisited neighbours and push

50
Breadth First Search
Step 5: Remove node 2 from the front of queue and visit the unvisited neighbours and push them
into queue.

Remove node 2 from the front of queue and visit the


unvisited neighbours and push them into queue.

51
Breadth First Search
Step 6: Remove node 3 from the front of queue and visit the unvisited neighbours and push them into
queue.
As we can see that every neighbours of node 3 is visited, so move to the next node that are in the front
of the queue.

Remove node 3 from the front of queue and visit the unvisited
neighbours and push them into queue.

52
Breadth First Search
Steps 7: Remove node 4 from the front of queue and visit the unvisited neighbours and push them
into queue.
As we can see that every neighbours of node 4 are visited, so move to the next node that is in the
front of the queue.

➢ Remove node 4 from the front of queue and visit the unvisited neighbors and push them
into queue.
➢ Now, Queue becomes empty, So, terminate these process of iteration.

53
Depth First Search
❑ Depth first Search or Depth first traversal is a recursive algorithm for searching all the
vertices of a graph or tree data structure. Traversal means visiting all the nodes of a graph.

❑ A standard DFS implementation puts each vertex of the graph into one of two categories:
❑ Visited
❑ Not Visited

❑ The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

54
Depth First Search

55
Depth First Search
The DFS algorithm works as follows:

1.Start by putting any one of the graph's vertices on top of a stack.

2.Take the top item of the stack and add it to the visited list.

3.Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the top of the stack.

4.Keep repeating steps 2 and 3 until the stack is empty.

56
Depth First Search
Let's see how the Depth First Search algorithm works with an example. We use an
undirected graph with 5 vertices.

undirected graph with 5 vertices.

57
Depth First Search
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.

58
Depth First Search
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.

59
Depth First Search
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and
visit it.

60
Depth First Search

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.

61
Applications
➢ Google Maps use graphs to find the shortest path from one destination to another. (dijkstra’s algorithm)
➢ The Google Search/ recommendation engines uses graphs to determine the relevance of search results. (page
rank)
➢ World Wide Web is the biggest graph. All the links and hyperlinks are the nodes and their interconnection is the
edges. This is why we can open one webpage from the other. (BFS)
➢ Social Networks like facebook, twitter, etc. use graphs to represent connections between users. (BFS and DFS)
➢ The nodes we represent in our graphs can be considered as the buildings, people, group, landmarks or anything in
general , whereas the edges are the paths connecting them.

62
Biconnectivity
Biconnected graphs are the graphs which cannot be broken into two disconnected pieces
(graphs) by connecting single edge.

63
Properties of Biconnected Graph
▪ There are two disjoint paths between any two vertices.
▪ There exist simple cycle between two vertices.
▪ There should not be any cut vertex (It is the vertex which if we
remove then the graph becomes disconnected.

64
Euler circuits

In graph theory, famous problem known as Konigsberg bridge problem.


In this problem the main theme was to cross the seven bridges exactly
once to visit various cities.

The Swiss mathematician Leonhard Euler solved the problem in 1736.


From that, the concept of Euler circuit is developed.

Euler path: is a path in graph that visits every edge exactly once.
Euler Circuit: is an Euler Path which starts and ends on the
same vertex.

65
Euler circuits
The Euler circuit is A-B-E-A-D-B-C-E-D-C-A

A C

E D

Euler path: is a path in graph that visits every edge exactly once.
Euler Circuit: is an Euler Path which starts and ends on the
same vertex.

66
Topological Sort
This is direct implementation of decrease and conquer method.

Following are the steps to be followed in this algorithm,

1. From a given graph, find a vertex with no incoming edges. Delete it along with all the
edges outgoing from it. If there are more than one such vertices then break the tie
randomly.
2. Note the vertices that are deleted.
3. All these recorded vertices give topologically sorted list.
A C

B D

67
Topological Sort

Choose vertex B, because it has no incoming edge, delete it along with its adjacent edges.

Delete B Delete A Delete D


A C C
C

E E
E

D D

Delete E Delete C

E
Hence, the list after topological sorting will be B, A, D, C, E.

68
Topological Sort

A D

B E

Hence, the list after topological sorting will be B, A, C, D, E.

69
Dijkstra’s algorithm
✓ Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest
path problems having non-negative edge weight in the graphs i.e., it is to find the
shortest distance between two vertices on a graph.

✓ Shortest path can be calculated only for the weighted graphs.

70
71
72
73
74
75
Implementation of Dijkstra’s algorithm
for(i=0; i<n; i++)
#include<stdio.h>
{
#include<conio.h>
for(j=0; j<n; j++)
#define INFINITY 9999
{
#define MAX 10
scanf("%d",&G[i][j]);
void dijkstra(int G[MAX][MAX],int n,int startnode);
}
int main()
}
{
printf("\nEnter the starting node:");
int G[MAX][MAX],i,j,n,u;
scanf("%d",&u);
printf("Enter no. of vertices:");
dijkstra(G,n,u);
scanf("%d",&n);
return 0;
printf("\nEnter the adjacency matrix:\n");
}

76
Implementation of Dijkstra’s algorithm
void dijkstra(int G[MAX][MAX],int n,int //initialize pred[],distance[] and visited[]
startnode) for(i=0; i<n; i++)
{
{ dis[i]=cost[startnode][i];
pred[i]=startnode;
int cost[MAX][MAX],dis[MAX],pred[MAX]; visited[i]=0;
}
int visited[MAX],count,min_dis,nextnode,i,j;
dis[startnode]=0;
for(i=0; i<n; i++) visited[startnode]=1;
{ count=1;
for(j=0; j<n; j++) while(count<n-1)
{
{ min_dis=INFINITY;
if(G[i][j]==0) //nextnode gives the node at minimum
cost[i][j]=INFINITY; distance
for(i=0; i<n; i++)
else
{
cost[i][j]=G[i][j];
}
}
77
Implementation of Dijkstra’s algorithm
count++;
if(dis[i]<min_dis&&!visited[i]) }
{ }
min_dis=dis[i]; //print the path and distance of each node
nextnode=i; for(i=0; i<n; i++)
} {
} if(i!=startnode)
//check if a better path exists through nextnode {
visited[nextnode]=1; printf("\nDistance of node%d=%d",i,dis[i]);
for(i=0; i<n; i++) printf("\nPath=%d",i);
{ j=i;
if(!visited[i]) do
{ {
if(min_dis+cost[nextnode][i]<dis[i]) j=pred[j];
{ printf("<-%d",j);
dis[i]=min_dis+cost[nextnode][i]; }
pred[i]=nextnode; while(j!=startnode);
} }
} }
}

78
THANK YOU!!!

79

You might also like