Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Module-5 Graph

Uploaded by

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

Module-5 Graph

Uploaded by

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

Vasantdada Patil Pratishthan’s College of

Engineering & Visual Arts, Sion, Mumbai.


Link based data
Data Structure
structure for graph(DS )
(CSC303)
Undirected Graph
S.E. A Div SEM-III(Computer Engineering)
Adjacency Lists
16
MODULE NO. 5
V= {1,2,3,4,5,6} GRAPH
E= {(1,2), (1,5),
(2,5), (2,3),
(3,4), TOPIC
(4,5), (4,6)}
1
35
Search Trees-AVL, rotations in AVL Tree, operations on AVL
2
Tree, Introduction
5 of B Tree, B+ Tree.

11/28/2021 By Mrs. Prajakta S. Khelkar 1


What is an Graph?

▪ Graph is non-linear data structure


▪ Graph is set of Vertices(V) and set of Edges(E).
▪ V set should be finite and non zero
▪ E is set of pair of vertices representing edges

G= (V,E)

V(G) = Vertices of Graph


E(G)= Edges of Graph

Example of Graphs are -


Example of Graphs are -

The following is a graph with 5 vertices and 6 edges.


This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E =
{(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}

V(G3) = Find ?
E(G3) = Find ?
Graph Terminology
1.Vertex : An individual data element of a graph is called as
Vertex. Vertex is also known as node. In above example graph,
A, B, C, D & E are known as vertices.
2.Edge : An edge is a connecting link between two vertices. Edge is
also known as Arc. An edge is represented as (starting Vertex,
ending Vertex).
In above graph, the link between vertices A

and B is represented as (A,B). Edges are

three types:

1.Undirected Edge - An undirected edge is a bidirectional edge. If


there is an undirected edge between vertices A and B then edge (A ,
B) is equal to edge (B , A).
2.Directed Edge - A directed edge is a unidirectional edge. If there
is a directed edge between vertices A and B then edge (A , B) is
not equal to edge (B , A).
11/28/2021 4
Applications of Graph
▪ Recommendations on e-commerce websites: The “Recommendations for
you” section on various e-commerce websites uses graph theory to
recommend items of similar type to user’s choice.
▪ Graph theory is also used to study molecules in chemistry and physics.
▪ Graph data structures are used in building a networks. In providing LAN
connections between nodes and also in VPN. Specially spanning tree is
used in these networks
▪ Finding Shortest path in networks, Internet etc
▪ Travelling Salesman Problem
▪ Graph theory is already used in airline network which connects countless
cities in most efficient way
▪ Minimizing Connections between transistors in Integrated Circuits
▪ Almost all types of Navigation Systems
▪ Document / Directory linking in computers or digital systems
▪ Dependency between tables in databases
Applications of Graph
▪ In Computer science graphs are used to represent the flow of
computation.
▪ Google/ Bing/ Yahoo maps uses graphs for building transportation
systems, where intersection of two (or more) roads (City) are
considered to be a vertex and the road connecting two vertices is
considered to be an edge, thus their navigation system is based on the
algorithm to calculate the shortest path between two vertices.
▪ In Facebook / Social Networking Sites, users are considered to be the
vertices and if they are friends then there is an edge running between
them. Facebook’s Friend suggestion algorithm uses graph theory.
▪ In Operating System, we come across the Resource Allocation Graph
where each process and resources are considered to be vertices. Edges
are drawn from resources to the allocated process, or from requesting
process to the requested resource. If this leads to any formation of a
cycle then a deadlock will occur.
Graph Terminology
Vertex
A individual data element of a graph is called as Vertex. Vertex is also known
as node. In above example graph, A, B, C, D & E are known as vertices.

Edge
An edge is a connecting link between two vertices. Edge is also known as Arc. An
edge is represented as (starting Vertex, ending Vertex). For example, in above
graph, the link between vertices A and B is represented as (A,B).

Edges are three types.


Undirected Edge - An undirected edge is a bidirectional edge. If there is a
undirected edge between vertices A and B then edge (A , B) is equal to edge (B, A)
Directed Edge - A directed edge is a unidirectional edge. If there is a directed
edge between vertices A and B then edge (A , B) is not equal to edge (B , A).
Weighted Edge - A weighted edge is an edge with cost on it.
Graph Terminology
Undirected Graph
A graph with only undirected edges is said to be undirected graph.

Directed Graph
A graph with only directed edges is said to be directed graph.

Mixed Graph
A graph with undirected and directed edges is said to be mixed graph.

End vertices or Endpoints


The two vertices joined by an edge are called the end vertices (or endpoints)
of the edge.

Origin
If an edge is directed, its first endpoint is said to be origin of it.

Destination
If an edge is directed, its first endpoint is said to be origin of it and the other
endpoint is said to be the destination of the edge.
Graph Terminology
Adjacent
If there is an edge between vertices A and B then both A and B are said to
be adjacent. In other words, Two vertices A and B are said to be adjacent if
there is an edge whose end vertices are A and B.

Incident
An edge is said to be incident on a vertex if the vertex is one of the
endpoints of that edge.

Outgoing Edge
A directed edge is said to be outgoing edge on its origin vertex.

Incoming Edge
A directed edge is said to be incoming edge on its destination vertex.

Degree
Total number of edges connected to a vertex is said to be degree of that
vertex.
Indegree
Total number of incoming edges connected to a vertex is said to be indegree
of that vertex.
Outdegree
Total number of outgoing edges connected to a vertex is said to be outdegree
of that vertex.

Parallel edges or Multiple edges


If there are two undirected edges to have the same end vertices, and for two
directed edges to have the same origin and the same destination. Such edges
are called parallel edges or multiple edges.

Self-loop
An edge (undirected or directed) is a self-loop if its two endpoints coincide.

Simple Graph
A graph is said to be simple if there are no parallel and self-loop edges.

Path
A path is a sequence of alternating vertices and edges that starts at a vertex
and ends at a vertex such that each edge is incident to its predecessor and
successor vertex.
11/28/2021 11
3.Weighted Edge - A weighted edge is an edge with cost on it.
Types of Graphs 1.Undirected Graph
A graph with only undirected edges is said to be undirected graph.

2.Directed Graph
A graph with only directed edges is said to be directed graph.
3.Complete Graph
A graph in which any V node is adjacent to all other nodes present in
the graph is known as a complete graph. An undirected graph contains
the edges that are equal to edges = n(n-1)/2 where n is the number of
vertices present in the graph. The following figure shows a complete
graph.
4.Regular Graph
Regular graph is the graph in which nodes are adjacent to each other, i.e., each
node is accessible from any other node.

5.Cycle Graph
A graph having cycle is called cycle graph. In this case the first and last nodes are
the same. A closed simple path is a cycle.
Sub Graph
A graph S is said to be a sub graph of a graph G if all the vertices and all the
edges of S are in G, and each edge of S has the same end vertices in S as in
G. A subgraph of G is a graph G’ such that V(G’)  V(G) and E(G’)  E(G)

In the above graph,the indegree of vertices v1, v3 is 2, indegree of vertices v2, v5 is 1 and indegree of v4 is
zero.
Connected Graph
A graph G is said to be connected if there is at least one path between
every pair of vertices in G. Otherwise,G is disconnected.

In the above graph,the indegree of vertices v1, v3 is 2, indegree of vertices v2, v5 is 1 and indegree of v4 is
zero.
A connected graph G A disconnected graph G
This graph is disconnected because the vertex v1 is not connected with the
other vertices of the graph.
Degree
In an undirected graph, the number of edges connected to a node is called the
degree of that node or the degree of a node is the number of edges incident on
it.
In the above graph, degree of vertex v1 is 1, degree of vertex v2 is 3, degree
of v3 and v4 is 2 in a connected graph.
Indegree
The indegree of a node is the number of edges connecting to that node or in
other words edges incident to it.
In the graph , the indegree of vertices v1, v3 is 2, indegree of vertices v2, v5 is 1
and indegree of v4 is zero.

11/28/2021 17
Graph Representations
Graph data structure is represented using following representations...
Adjacency Matrix
Incidence Matrix
Adjacency List

Adjacency Matrix
In this representation, graph can be represented using a matrix of size total
number of vertices by total number of vertices. That means if a graph with 4
vertices can be represented using a matrix of 4X4 class.
In this matrix, rows and columns both represents vertices. This matrix is
filled with either 1 or 0. Here, 1 represents there is an edge from row vertex
to column vertex and 0 represents there is no edge from row vertex to
column vertex.
For example, consider the following undirected graph representation...
Array based data structure for
Undirected Graph graph
Adjacency Matrix
1 2 3 4 5 6

1 0 1 0 0 1 0

2 1 0 1 0 1 0

3 0 1 0 1 0 0

4 0 0 1 0 1 1
V= {1,2,3,4,5,6}
E= {(1,2), (1,5), 5 1 1 0 1 0 0
(2,5), (2,3),
6 0 0 0 1 0 0
(3,4),
(4,5), (4,6)}
Size = O(𝑛2)
1
9
11/28/2021 20
Array based data structure for
graph
Advantage of Adjacency Matrix :
• Determining whether there is an edge from x to y in O(1) time
for any two vertices x and y.

Disadvantage of Adjacency Matrix :


• Computing all neighbors of a given vertex x in O(𝒏) time
• It takes O(𝒏𝟐) space.

2
1
Directed graph representation...

Incidence Matrix
In this representation, graph can be represented using a matrix of size total number
of vertices by total number of edges. That means if a graph with 4 vertices and 6
edges can be represented using a matrix of 4X6 class.

In this matrix, rows represents vertices and columns represents edges. This matrix
is filled with either 0 or 1 or -1. Here, 0 represents row edge is not connected to
column vertex, 1 represents row edge is connected as outgoing edge to column
vertex and -1 represents row edge is connected as incoming edge to column vertex.

For example, consider the following


directed graph representation...
Adjacency List
In this representation, every vertex of graph contains list of its adjacent vertices.

For example, consider the following directed graph representation implemented


using linked list...

This representation can also be implemented using array as follows..


Link based data structure for
Undirected Graph
graph
Adjacency Lists

1 2 5

2 1 3 5

3 2 4

4 3 5 6
V= {1,2,3,4,5,6}
E= {(1,2), (1,5), 5 1 2 4
(2,5), (2,3),
6 4
(3,4),
(4,5), (4,6)}
Size = O(𝑛 + 𝑚)
2
4
Which data structure is commonly used for
storing graphs ?
• Reasons: Adjacency lists

• Graphs in real life are sparse (𝒎 ≪ 𝒏𝟐).

• Most algorithms require processing


neighbors of each vertex.

• ➔Adjacency matrix will enforce O(𝒏𝟐) bound on time complexity


for such algorithm.

2
• But, there are a few 5
3.Adjacency Multilists
In the adjacency-list representation of an undirected graph each edge (u, v) is
represented by two entries one on the list for u and the other on tht list for v. As we
shall see in some situations it is necessary to be able to determin ie ~ nd enty for a
particular edge and mark that edg as having been examined. This can be
accomplished easily if the adjacency lists are actually maintained as multilists (i.e.,
lists in which nodes may be shared among several lists). For each edge there will be
exactly one node but this node will be in two lists (i.e. the adjacency lists for each
of the two nodes to which it is incident).
For adjacency multilists, node
structure is typedef struct edge
*edge_pointer; typedef struct edge
{
short int marked; int
vertex1, vertex2;
edge_pointer path1, path2;
};
edge_pointer graph[MAX_VERTICES];

11/28/2021 26
Lists: vertex 0: N0->N1->N2, vertex 1: N0->N3->N4 vertex 2: N1->N3-
>N5, vertex 3: N2->N4->N5

11/28/2021 27
Figure: Adjacency multilists for given graph

4. Weighted edges
In many applications the edges of a graph have weights assigned to them. These
weights may represent the distance from one vertex to another or the cost of going
from one; vertex to an adjacent vertex In these applications the adjacency matrix
entries A [i][j] would keep this information too. When adjacency lists are used the
weight information may be kept in the list’nodes by including an additional field
weight. A graph with weighted edges is called a network.

11/28/2021 28
Graph traversal
Definition:
A vertex y is said to be reachable from x if there is a path from x to y.

Graph traversal from vertex x: Starting from a given vertex x,


the aim is to visit all vertices which are reachable from x.
2
9
Operation on Graph
• Insert on edge
• Remove on edge
• Display the adjacency matrix/list
• Traversal a graph

11/28/2021 30
Traversal a graph
• Depth first traversal
• Breadth first traversal

11/28/2021 31
ELEMENTARY GRAPH OPERATIONS
Given a graph G = (V E) and a vertex v in V(G) we wish to visit all vertices in G
that are reachable from v (i.e., all vertices that are connected to v). We shall look at
two ways of doing this: depth-first search and breadth-first search. Although these
methods work on both directed and undirected graphs the following discussion
assumes that the graphs are undirected.
Depth-First Search

• Begin the search by visiting the start vertex v


o If v has an unvisited neighbor, traverse it recursively
o Otherwise, backtrack
• Time complexity
o Adjacency list: O(|E|) 2
o Adjacency matrix: O(|V| )
We begin by visiting the start vertex v. Next an unvisited vertex w adjacent to v is
selected, and a depth-first search from w is initiated. When a vertex u is reached such
that all its adjacent vertices have been visited, we back up to the last vertex visited
that has an unvisited vertex w adjacent to it and initiate a depth-first search from w.
The search terminates when no unvisited vertex can be reached from any of the visited
vertices.
DFS traversal of a graph, produces a spanning tree as final result. Spanning Tree is
a graph without any loops. We use Stack data structure with maximum size of
11/28/2021
total number of vertices in the graph to implement DFS 32
traversal of a graph.

We use the following steps to implement DFS traversal...


Step 1: Define a Stack of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex and push it
on to the Stack.
Step 3: Visit any one of the adjacent vertex of the verex which is at top of the stack
which is not visited and push it on to the stack.
Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top
of the stack.
Step 5: When there is no new vertex to be visit then use back tracking and

pop one vertex from the stack. Step 6: Repeat steps 3, 4 and 5 until stack

becomes Empty.

Step 7: When stack becomes Empty, then produce final spanning tree by removing

unused edges from the graph This function is best described recursively as in

Program.
11/28/2021 33
This function is best described recursively as in Program.
#define FALSE 0
#define TRUE 1
int visited[MAX_VERTICES];
void dfs(int v)
{
node_pointer w;
visited[v]= TRUE;
printf(“%d”, v);
for (w=graph[v]; w; w=w-
>link) if (!visited[w->vertex])
dfs(w->vertex);
}
Consider the graph G of Figure 6.16(a), which is represented by its adjacency lists as
in Figure 6.16(b). If a depth- first search is initiated from vertex 0 then the vertices of
G are visited in the following order: 0 1 3 7 4 5 2 6. Since DFS(O) visits all vertices
that can be reached from 0 the vertices visited, together with all edges in G
incident to these vertices form a connected component of G.

11/28/2021 34
Figure: Graph and its adjacency list representation, DFS spanning tree
Analysis or DFS:
When G is represented by its adjacency lists, the vertices w adjacent to v can be
determined by following a chain of links. Since DFS examines each node in the
adjacency lists at most once and there are 2e list nodes the time to complete the
search is O(e). If G is represented by its adjacency matrix then the time to
determine all vertices
2
adjacent to v is O(n). Since at most n vertices are visited
the total time is O(n ).

11/28/2021 35
11/28/2021 36
11/28/2021 37
Breadth-First Search
In a breadth-first search, we begin by visiting the start vertex v. Next all
unvisited vertices adjacent to v are visited. Unvisited vertices adjacent to
these newly visited vertices are then visited and so on. Algorithm BFS
struct queue *queue_pointer; typedef struct queue {
int vertex;

We use the following steps to implement BFS traversal...


Step 1: Define a Queue of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex and insert it
into the Queue.
Step 3: Visit all the adjacent vertices of the vertex which is at front of the Queue
which is not visited and insert them into the Queue.
Step 4: When there is no new vertex to be visit from the vertex at front of the Queue
then delete that vertex from
the Queue.
Step 5: Repeat step 3 and 4 until queue becomes empty.
Step 6: When queue becomes Empty, then produce final spanning tree by removing
unused edges from the graph
Analysis Of BFS:
Each visited vertex enters the queue exactly once. So the while loop is iterated at
most n times If an adjacency matrix is used the loop takes O(n) time for each
vertex visited. The total time is therefore, O(n2). If adjacency lists are used the loop
has a total cost of d0 + … + dn-1 = O(e), where d is the degree of vertex i. As in the
case of DFS all visited vertices together with all edges incident to them, form a
connected component of G.
11/28/2021 38
11/28/2021 39
11/28/2021 40
11/28/2021 41
Implementation of BFS
#include<stdio.h>
int a[20][20],q[20],visited[20],n,f=-1,r=-1;
void bfs(int v)
{ int i;
for (i=0;i<n;i++) // check all the vertices in the graph
{ if(a[v][i] != 0 && visited[i] == 0) // adjacent to v and not visited
{
r=r+1;
q[r]=i; // insert them into queue
visited[i]=1; // mark the vertex visited
printf("%d ",i);
}
}
f=f+1; // remove the vertex at front of the queue
if(f<=r) // as long as there are elements in the queue
bfs(q[f]); // peform bfs again on the vertex at front of the queue
}

11/28/2021 42
int main()
{ int v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=0;i<n;i++) // mark all the vertices as not visited
{
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=0;i<n;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
f=r=0;
q[r]=v;
printf("\n BFS traversal is:\n");
visited[v]=1; // mark the starting vertex as visited
printf("%d ",v);
bfs(v);
if(r != n-1)
printf("\n BFS is not possible");
}
11/28/2021 43
11/28/2021 44
• Construct adjacency matrix & adjacency list for
the graph

11/28/2021 45
11/28/2021 46
Topological Sorting:

11/28/2021 47
11/28/2021 48
11/28/2021 49
Directed Acyclic Graph

11/28/2021 50
Algorithm

11/28/2021 51
Example
Applications
11/28/2021 60
11/28/2021 61
11/28/2021 62
11/28/2021 63

You might also like