0% found this document useful (0 votes)
63 views32 pages

Graphs

The document discusses graphs and graph data structures. It defines a graph as consisting of vertices (nodes) connected by edges. Common graph operations include finding paths between nodes and shortest paths. Graphs are implemented using adjacency matrices, adjacency lists, and path matrices. The shortest path algorithm uses a path matrix to find the shortest distance between all pairs of vertices in the graph.

Uploaded by

Puneet Mittal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
63 views32 pages

Graphs

The document discusses graphs and graph data structures. It defines a graph as consisting of vertices (nodes) connected by edges. Common graph operations include finding paths between nodes and shortest paths. Graphs are implemented using adjacency matrices, adjacency lists, and path matrices. The shortest path algorithm uses a path matrix to find the shortest distance between all pairs of vertices in the graph.

Uploaded by

Puneet Mittal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

Graphs

MODULE 5
Graphs
➢Non Linear Data Structure
➢It is similar to the mathematical graph structure, which comprises of a set of vertices
connected with each other through edges.
➢Some of the typical operations performed on a graph data structure include finding
possible paths between two nodes and finding the shortest possible path.
➢Graph data structure finds its application in varied domains, such as computer
network analysis, travel application, chip designing, gaming and so on.
BASIC CONCEPT
➢A graph G consists of the following elements:
➢ A set of V, vertices or nodes where V={v1, v2, v3…., vn}
➢ A set of E, edges also called arcs where E={e1, e2, e3…., en}

➢Here, G=(V,E)

➢e1 is an edge between v1 and v2 vertices while e2 is an edge between v2 and v3 vertices.

➢Thus, we can generically represent an edge as e={u,v) where e connects both u and v vertices

➢e=(u,v) is same as e=(v,u) → Undirected Graph


Directed Graph
If we replace each edge of the Graph G with arrows, then it will become a
directed graph or diagraph.
The set of vertices and edges are:
GRAPH TERMINOLOGY
GRAPH IMPLEMENTATION
➢Graphs are nothing but a collection of nodes and edges. Thus, while representing graphs in memory the
only focus is on capturing details related to the different vertices and edges.

➢Graphs can be implemented using the following methods:


1. Adjacency matrix
2. Path matrix
3. Adjacency list
Implementing Graphs Using
Adjacency Matrix
The adjacency matrix of graph G is defined as an N X N matrix A, where:

1. Ai,j = 1, if there is an edge from vertex vi to vj

2. and Ai,j =0 if there is no edge from vertex vi to vj


C program to represent adjacency
matrix
void main() /*Printing Adjacency Matrix*/ Output
{ int A[5][5]; printf(“Adjacency Matrix:”); Adjacency Matrix:
int i,j; for(i=0;i<5;i++) 11010
clrscr(); { printf(“\n”); 00100
for(i=0;i<5;i++) 00001
for(j=0;j<5;j++)
for(j=0;j<5;j++) 00100
printf(“%d “,A[i][j]); } 00000
A[i][j]=0; getch();
A[0][0]=1; }
A[0][1]=1;
A[0][3]=1;
A[1][2]=1;
A[2][4]=1;
A[3][2]=1;
Advantages and Disadvantages
➢The advantage of adjacency matrix representation of a graph is that it is simple to implement.

Disadvantages
➢It requires O(n2) memory space even if the adjacency matrix is sparse.

➢It proves to be inefficient representation of graphs that have large number of vertices.
Implementing Graphs Using Path
Matrix
The Path Matrix of Graph G is defined as an N X N matrix P, where:
▪ Pi,j=1, if there is a path from vertex vi to vj, and
▪ Pi,j=0, if there is no path from vertex vi to vj

Now, the path matrix P can be deduced using the adjacency matrix of G, as depicted below:

PN =A+A2 + A3 + …. + AN

Here, A2 is the square of the adjacency matrix A, A3 is the cube of A, and so on.

All the non-zero entries resulting from the addition operation above are replaced by 1 to arrive at the path
matrix.

This method of deriving the path matrix by computing powers of adjacency matrix is not very efficient, as it
requires performing a number of matrix multiplication operations
Warshall’s Method for Path Matrix
Warshall’s method determines the presence of a path between vi and vj by

1. identifying a direct path from vi to vj, and

2. identifying an indirect path from vi and vj that is, a path from vi to vk and vk to vj.

That is, Pi, j =P i, j OR (P i, k AND Pk, j )

Here, OR represents the logical OR operation and AND represents the logical AND operation.
Warshall’s algorithm
path_matrix(Adjacency Matrix A[], N)
Step 1: Start
Step 2: Set P[] = A[]
Step 3: Set i = j = k = 1
Step 4: Repeat Steps 5-10 while k <=N
Step 5: Repeat Steps 6-9 while i <=N
Step 6: Repeat Steps 7-8 while j <=N
Step 7: P[i,j] = P[i,j] OR (P[i,k] AND P[k,j])
Step 8: j = j + 1
Step 9: i = i + 1
Step 10: k = k + 1
Step 11: Display path matrix P[]
Step 12: Stop
int AND(int x, int y)
void main() for(i=0;i<5;i++)
{
{ for(j=0;j<5;j++)
return(x*y);
int A[5][5], P[5][5]; P[i][j]=A[i][j];
}
int i,j,k;
int OR(int x, int y)
clrscr(); /*Creating path matrix*/
{
for(i=0;i<5;i++)
if(x==0 && y==0)
for(j=0;j<5;j++) for(k=0;k<5;k++)
return(0);
A[i][j]=0; for(i=0;i<5;i++)
else
/*Creating adjacency matrix*/ for(j=0;j<5;j++)
return(1);
A[0][0]=1; P[i][j]=OR(P[i][j],AND(P[i][k],P[k][j]));
A[0][1]=1; }
A[0][3]=1; /*Printing path matrix*/
A[1][2]=1;
A[2][4]=1; printf(“\n\nPath Matrix: \n”);
A[3][2]=1; for(i=0;i<5;i++)
/*Printing adjacency matrix*/ {
printf(“Adjacency Matrix: \n”); printf(“\n”);
for(i=0;i<5;i++) for(j=0;j<5;j++)
{ printf(“\n”); printf(“%d “,P[i][j]);}
for(j=0;j<5;j++) getch(); }
printf(“%d “,A[i][j]); }
Implementing Graphs Using
Adjacency List
Adjacency list is a linked representation of a graph.

It consists of a list of graph nodes with each node itself consisting of a linked list of its neighboring nodes.
#include<stdio.h> for(j=0;j<N;j++) void display(int num){
#include<conio.h> { int i,j;
#include<stdlib.h> fflush(stdin); printf(“\n”);
struct vertex printf(“Edge from %d to %d? (y/n): “,i+1,j+1); for(i=0;i<num;i++)
{ scanf(“%c”,&ch); {
int id; if(ch==’y’) printf(“Edges of node[%d] are: “,i+1);
struct vertex *edge[10]; node[i].edge[j]=&node[j]; for(j=0;j<num;j++)
}node[10]; else {
node[i].edge[j]=NULL;} } if(node[i].edge[j]==NULL)
void main() display(N); continue;
{ getch(); } printf(“(%d-%d) “,i+1,node[i].edge[j]->id+1);
int i,j,N; }
char ch; printf(“\n”);
clrscr(); }
i=j=N=0; }
printf(“Enter number of graph vertices: “);
scanf(“%d”,&N);
for(i=0;i<N;i++)
{ node[i].id=i;
fflush(stdin);
SHORTEST PATH ALGORITHM
One of the most common problems associated with graphs is to find the shortest path from one node to
the other.

For example, consider a scenario where a freight carrier departing from Delhi is required to drop
consignments at Lucknow, Jaipur, Ahmedabad, Pune, and Hyderabad airports.

In this situation, the route taken by the carrier is determined by assessing the distance between each

of these cities.

The final route undertaken should be the shortest path that covers all these cities.
Derive Path Matrix
A modification of the Warshall’s algorithm can be applied to the weight matrix to derive the shortest path
matrix SP that represents the weight of the shortest possible path between any two nodes of a graph.

Replace 0 with ∞

SPi,j 1 2 3 4 5
1 8 3 ∞ 4 ∞
2 ∞ ∞ 7 ∞ ∞
3 4 ∞ ∞ ∞ 5
4 ∞ ∞ 2 ∞ ∞
5 ∞ ∞ ∞ 1 ∞
Shortest Path Matrix
the following relation is applied to arrive at the shortest path matrix:

SPi,j 1 2 3 4 5
1 8 3 ∞ 4 ∞
2 ∞ ∞ 7 ∞ ∞
3 4 ∞ ∞ ∞ 5
4 ∞ ∞ 2 ∞ ∞
5 ∞ ∞ ∞ 1 ∞
Shortest Path Algorithm
shortest_path_matrix(Path Matrix P[], N) Step 11: Repeat Steps 12-17 while k<=N
Step 1: Start Step 12: Repeat Steps 13-16 while i <=N
Step 2: Set i = j = 1 Step 13: Repeat Steps 14-15 while j <=N
Step 3: Repeat Steps 4-9 while i<=N Step 14: SP[i,j] = MINIMUM(SP[i,j], SP[i,k]+SP[k,j]
Step 4: Repeat Steps 5-8 while j<=N Step 15: j = j + 1
Step 5: if P[i,j]=0 goto Step 6 else goto Step 7 Step 16: i = i + 1
Step 6: Set SP[i,j]= 8 Step 17: k = k + 1
Step 7: Set SP[i,j]=P[i,j] Step 18: Display shortest path matrix SP[]
Step 8: j = j + 1 Step 19: Stop
Step 9: i = i + 1
Step 10: Set i = j = k = 1
void main() printf(“Path Matrix: \n”); printf(“\n\nShortest Path Matrix: \n”);
{ for(i=0;i<5;i++) for(i=0;i<5;i++)
int P[5][5], SP[5][5]; { {
int i,j,k; printf(“\n”); printf(“\n”);
clrscr(); for(j=0;j<5;j++) for(j=0;j<5;j++)
for(i=0;i<5;i++) printf(“%d\t”,P[i][j]); printf(“%d\t”,SP[i][j]);
for(j=0;j<5;j++) } }
P[i][j]=0; for(i=0;i<5;i++) getch(); }
P[0][0]=8; for(j=0;j<5;j++)
P[0][1]=3; if(P[i][j]==0) int MIN(int x, int y)
P[0][3]=4; SP[i][j]=999; {
P[1][2]=7; else if(x<=y)
P[2][0]=4; SP[i][j]=P[i][j]; return(x);
P[2][4]=5; for(k=0;k<5;k++) else
P[3][2]=2; for(i=0;i<5;i++) return(y);
P[4][3]=1; for(j=0;j<5;j++) }
SP[i][j]=MIN(SP[i][j],SP[i][k]+SP[k][j]);
GRAPH TRAVERSAL
There are two methods of traversing a graph:
➢Breadth First Search (BFS)
➢Depth First Search (DFS)
Graph Traversal
Both these methods consider the graph nodes to be in one of the following
states at any given point of time:
1. Ready state
2. Waiting state
3. Processed state

The state of a node keeps on changing as the graph traversal progresses.


Once the state of a node becomes processed, it is considered as traversed or
visited.
Breadth First Search
➢The BFS method begins with analyzing the starting node and then progresses by analysing its adjacent or
neighbouring nodes.

➢Once all the neighbouring nodes of the starting node are analyzed, the algorithm starts analyzing the
neighboring nodes of each of the analyzed neighboring nodes.

➢This method of graph traversal requires frequent backtracking to the already analyzed nodes.

➢ As a result, a data structure is required for storing information related to the neighboring nodes. (i.e.
Queue)

➢The BFS method uses the queue data structure for storing the nodes data.
The BFS traversal sequence for the above graph will be: v1, v2, v3, v4, v5, v6, v7, v8.

Another BFS traversal sequence can be: v1, v3, v2, v6, v5, v4, v7, v8.
BFS Algorithm
BFS(adj[], status[], queue[], N)
Step 1: Start
Step 2: Set status[] = 1
Step 3: Push(queue, v1)
Step 4: Set status[v1]=2
Step 5: Repeat Step 6–11 while queue[] is not empty
Step 6: V = Pop(queue)
Step 7: status[V]=3
Step 8: Repeat Step 9-11 while adj(V) is not empty
Step 9: If adj(V) = 1 goto step 10 else goto step 8
Step 10: Push(queue, adj(V))
Step 11: Set adj[v]=2
Step 12: Stop
Depth First Search
➢The DFS method visits the graph nodes along the different paths.
➢It begins analyzing the nodes from the start to the end node and then proceeds along
the next path from the start node.
➢This process is repeated until all the graph nodes are visited.
➢The DFS method also requires frequent backtracking to the already analyzed nodes.
➢It uses the stack data structure for storing information related to the previous nodes.
The DFS traversal sequence for this graph will be: v1, v2, v4, v8, v5, v7, v3, v6.

Another DFS traversal sequence can be: v1, v3, v6, v7, v8, v2, v5, v4.
DFS Algorithm
DFS(adj[], status[], stack[], N)
Step 1: Start
Step 2: Set status[] = 1
Step 3: Push(stack, v1)
Step 4: Set status[v1]=2
Step 5: Repeat Step 6–11 while stack[] is not empty
Step 6: V = Pop(stack)
Step 7: status[V]=3
Step 8: Repeat Step 9-11 while adj(V) is not empty
Step 9: If adj(V) = 1 goto step 10 else goto step 8
Step 10: Push(stack, adj(V))
Step 11: Set adj[v]=2
Step 12: Stop

You might also like