0% found this document useful (0 votes)
6 views28 pages

Unit 4

Graph data structure

Uploaded by

Dr. S.K. Sajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views28 pages

Unit 4

Graph data structure

Uploaded by

Dr. S.K. Sajan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Unit IV: Graphs: DEFINITION-REPRESENTATION OF GRAPH-TYPES OF www.padeepz.

net
GRAPH-BREADTH FIRST TRACERSAL-EPTH FIRST TRAVERSAL -TOPOLOGICAL
SORT-BI-CONNECTIVITY-CUT VERTEX-EUCLER CIRCUITS-APPLICATIONS OF HEAP.

Graph: - A graph is data structure that consists of following two components.


 A finite set of vertices also called as nodes.
 A finite set of ordered pair of the form (u, v) called as edge.
(or)
A graph G=(V, E) is a collection of two sets V and E, where
V Finite number of vertices
E Finite number of Edges,

Edge is a pair (v, w), where v, w ∈ V.

Application of graphs:
 Coloring of MAPS
 Representing network
o Paths in a city
o Telephone network o
Electrical circuits etc.
 It is also using in social network
including o LinkedIn
o Facebook
Types of Graphs:
 Directed graph
 Undirected Graph

Directed Graph:
In representing of graph there is a directions are
shown on the edges then that graph is called
Directed graph.
That is,
A graph G=(V, E) is a directed graph ,Edge is a

pair (v, w), where v, w ∈ V, and the pair is ordered.


Means vertex ‘w’ is adjacent to v.
Directed graph is also called digraph.

Undirected Graph:
In graph vertices are not ordered is called undirected
graph. Means in which (graph) there is no direction
(arrow head) on any line (edge).
A graph G=(V, E) is a directed graph ,Edge is a pair

(v, w), where v, w ∈ V, and the pair is not ordered.


Means vertex ‘w’ is adjacent to ‘v’, and vertex ‘v’ is
adjacent to ‘w’
www.padeep z.net
Note: in graph there is another component
www.padeepz.net
called weight/ cost.

Weight graph:
Edge may be weight to show that there is
a cost to go from one vertex to another.
Example: In graph of roads (edges) that
connect one city to another (vertices), the
weight on the edge might represent the
distance between the two cities (vertices).

www.padeepz.net
www.padeepz.net
Difference between Trees and Graphs
Trees Graphs
Path Tree is special form of graph i.e. minimally In graph there can be more than
connected graph and having only one path one path i.e. graph can have uni-
between any two vertices. directional or bi-directional paths
(edges) between nodes
Loops Tree is a special case of graph having Graph can have loops, circuits as
no loops, no circuits and no self-loops. well as can have self-loops.
Root Node In tree there is exactly one root node and In graph there is no such concept
every child have only one parent. of root node.
Parent In trees, there is parent child relationship so In Graph there is no such parent
Child flow can be there with direction top to child relationship.
relationship bottom or vice versa.
Complexity Trees are less complex then graphs as having Graphs are more complex in
no cycles, no self-loops and still connected. compare to trees as it can have
cycles, loops etc
Types of Tree traversal is a kind of special case of Graph is traversed by
Traversal traversal of graph. Tree is traversed in Pre- DFS: Depth First Search
Order, In-Order and Post-Order(all three BFS : Breadth First Search
in DFS or in BFS algorithm) algorithm
Connection In trees, there are many rules / restrictions In graphs no such rules/
Rules for making connections between nodes restrictions are there for
through edges. connecting the nodes through
edges.
DAG Trees come in the category of DAG : Graph can be Cyclic or Acyclic.
Directed Acyclic Graphs is a kind of
directed graph that have no cycles.
Different Different types of trees are : Binary Tree , There are mainly two types of
Types Binary Search Tree, AVL tree, Heaps. Graphs :Directed and Undirected
graphs.
Applications Tree applications: sorting and searching like Graph applications : Coloring of
Tree Traversal & Binary Search. maps, in OR (PERT & CPM),
algorithms, Graph coloring, job
scheduling, etc.
No. of edges Tree always has n-1 edges. In Graph, no. of edges depends on
the graph.
Model Tree is a hierarchical model. Graph is a network model.
Figure

www.padeepz.net
Other types of graphs:
www.padeepz.net
Complete Graph:
A complete graph is a simple undirected graph in which every pair of distinct vertices is
connected by a unique edge.
OR
If an undirected graph of n vertices consists of n(n-1)/2 number of edges then the graph is
called complete graph.
Example:
vertices Edges Complete graph vertices Edges Complete graph
n=2 1 n=6 15

n=3 3 n=7 21

n=4 6 n=5 10

www.padeepz.net
Sub graph:
www.padeepz.net
A sub-graph G' of graph G is a graph, such that the set of vertices and set of edges
of G' are proper subset of the set of vertices and set of edges of graph G
respectively.

Connected Graph:
A graph which is connected in the sense of a topological space (study of shapes), i.e., there is
a path from any point to any other point in the graph. A graph that is not connected is said to
be disconnected.

www.padeepz.net
Path:
www.padeepz.net
A path in a graph is a finite or infinite sequence of edges which connect a sequence of
vertices. Means a path form one vertices to another vertices in a graph is represented by
collection of all vertices (including source and destination) between those two vertices.

Cycle: A path that begins and ends at the same vertex.

Simple Cycle: a cycle that does not pass through other vertices more than once

Degree:
The degree of a graph vertex v of a graph G is the number of graph edges which touch v. The
vertex degree is also called the local degree or valency. Or

The degree (or valence) of a vertex is the number of edge ends at that vertex.

For example, in this graph all of the vertices have degree three.
In a digraph (directed graph) the degree is usually divided into the in-degree and the out-
degree
 In-degree: The in-degree of a vertex v is the number of edges with v as their terminal
vertex.
 Out-degree: The out-degree of a vertex v is the number of edges with v as their initial
vertex.

www.padeepz.net
www.padeepz.net

TOPOLOGICAL SORT
A topological sort is a linear ordering of vertices in a Directed Acyclic Graph
such that if there is a path from Vi to Vp, then Vj appears after Vi in the linear
ordering.Topological sort is not possible if the graph has a cycle.

INTRODUCTION

In graph theory, a topological sort or topological ordering of a directed


acyclic graph (DAG) is a linear ordering of its nodes in which each node
comes before all nodes to which it has outbound edges.
Every DAG has one or more topological sorts.
More formally, define the partial order relation R over the nodes of the
DAG such that xRy if and only if there is a directed path from x to y.
Then, a topological sort is a linear extension of this partial order, that is,
a total order compatible with the partial order.

PROCEDURE

Step – 1 : Find the indegree for every vertex.

Step – 2 : Place the vertice whose indegree is 0, on the empty queue.

Step – 3 : Dequeue the vertex V and decrement the indegrees of all its adjacent
vertices.

Step – 4 : Enqueue the vertex on the queue if its indegree falls to zero.

Step – 5 : Repeat from Step -3 until the queue becomes empty.

The topological ordering is the order in which the vertices dequeue.

Vertices Indegree
1 0
2 0

www.padeepz.net
www.padeepz.net

GRAPH TRAVERSAL
Graph traversal is the Visiting all the nodes of a graph.

The traversals are :

1. DFS (Depth First Search)


2. BFS (Breadth First Search)

BREADTH FIRST SEARCH

The Breadth first search was one of the systematic approaches for
exploring and searching the vertices/nodes in a given graph. The
approach is called "breadth-first" because from each vertex ‘v’ that we
visit, we search as broadly as possible by next visiting all the vertices
adjacent to v.
It can also be used to find out whether a node is reachable from a given
node or not.
It is applicable to both directed and undirected graphs.
Queue is used in the implementation of the breadth first search.

www.padeepz.net
www.padeepz.net
ALGORITHM

Procedure bfs()
{
//BFS uses Queue data structure
Queue q=new LinkedList();
q.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited=true;
while(!q.isEmpty())
{
Node n=(Node)q.remove(); Node child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}

Procedure

Step -1 Select the start vertex/source vertex. Visit the vertex and mark it
as one (1) (1 represents visited vertex).
Step -2 Enqueue the vertex.
Step -3 Dequeue the vertex.
Step -4 Find the Adjacent vertices.
Step -5 Visit the unvisited adjacent vertices and mark the distance as 1.
Step -6 Enqueue the adjacent vertices.
Step -7 Repeat from Step – 3 to Step – 5 until the queue becomes empty.

www.padeepz.net
www.padeepz.net
Ex : A B Vertices Visited
Vertices
A 1
C D B 0 1
C 0 1
D 0 1
Enqueue A B C D
Dequeue A B C D

A B
Vertices Visited
Vertices
C 1
C D A 0 1
B 0 1
D 0 1
E E 0 1
Enqueue C A B D
E
Dequeue C A B D
E

Pseudo Code :

void BFS(Vertex S)

Vertex v,w;

Queue Q;

visited[s] = 1; enqueue(S,Q);

while(!IsEmpty(a))

www.padeepz.net
www.padeepz.net
v = Dequeue(Q);

print(v);

for each adjacent vertices w to v

if(visited[w]==0)

visited[w] = 1;

Enqueue(w,Q);

APPLICATIONS

Breadth-first search can be used to solve many problems in graph theory, for
example.

Finding all nodes within one connected component


Copying Collection, Cheney's algorithm
Finding the shortest path between two nodes u and v (in an unweighted
graph)
Finding the shortest path between two nodes u and v (in a weighted
graph: see talk page)
Testing a graph for bipartiteness
(Reverse) Cuthill–McKee mesh numbering
Testing whether graph is connected.
Computing a spanning forest of graph.
Computing, for every vertex in graph, a path with the minimum number
of edges between start vertex and current vertex or reporting that no
such path exists.
Computing a cycle in graph or reporting that no such cycle exists.

Uses

www.padeepz.net
www.padeepz.net
Testing whether graph is connected.
Computing a spanning forest of graph.
Computing, for every vertex in graph, a path with the minimum number
of edges between start vertex and current vertex or reporting that no
such path exists.
Computing a cycle in graph or reporting that no such cycle exists.

DEPTH FIRST SEARCH


Depth first search works by taking a node, checking its neighbors,
expanding the first node it finds among the neighbors, checking if that
expanded node is our destination, and if not, continue exploring more
nodes.
In depth-first search, edges are explored out of the most recently
discovered vertex v that still has unexplored edges leaving it.
When all of v' s edges have been explored, the search "backtracks" to
explore edges leaving the vertex from which v was discovered.
This process continues until we have discovered all the vertices that are
reachable from the original source vertex.
If any undiscovered vertices remain, then one of them is selected as a
new source and the search is repeated from that source.

www.padeepz.net
www.padeepz.net
This entire process is repeated until all vertices are discovered.
Stack is used in the implementation of the depth first search.

In DFS, the basic data structures for storing the adjacent nodes is stack.

Procedure:

Step -1 Select the start vertex.


Step -2 Visit the vertex.
Step -3 Push the vertex on to the stack.
Step -4 Pop the vertex.
Step -5 Find the adjacent vertices, and select any 1 of them.
Step -6 Repeat from Step – 4 to Step – 5 until the stack becomes empty.

A B Vertices Visited Stack O/P


Vertices
A
A 1
C D B 0 1 D
C 0 1
A D C B D 0 1 C

A B Vertices Visited Stack o/p A BD C


Vertices
A 1
B 0 1
C D
C 0 1
D 0 1

www.padeepz.net
www.padeepz.net
Pseudo Code:

void DFS(Vertex S)

int top = 0;

Stack C; vertex v,w;

visited [S] = 1

C[top] = S;

while(!IsEmpty(C))

v = pop(C);

print(V);

for each unknown adjacent vertices of V,

if(visited[w] == 0)

visited[w] = 1;

push(w,C);

(OR)

www.padeepz.net
www.padeepz.net
void DFS(vertex V)

visited[v] = 1;

push(v);

pop(v);

for each w adjacent to V

if(!visited[w])

Dfs(w);

ALGORITHM

Procedure dfs()
{
//DFS uses Stack data structure
Stack s=new Stack();
s.push(this.rootNode);
rootNode.visited=true;
printNode(rootNode);
while(!s.isEmpty())
{
Node n=(Node)s.peek();
Node child=getUnvisitedChildNode(n);
if(child!=null)
{
child.visited=true;
printNode(child);
s.push(child);
}
else
{
s.pop();

www.padeepz.net
www.padeepz.net
}
}
//Clear visited property of nodes
clearNodes();
}

Applications of DFS :

1. To check whether the undirected graph is connected or not.


2. To check if the connected undirected graph is bi – connected or not.
3. To check whether the directed graph is acyclic or not.

I. Undirected Graph :
An undirected graph is connected if and only if a depth first search
starting from any node visits every node.

A 1. Tree Edge

2. Back Edge ----------- >

B D E

A A

C B B

C E C

D D

B A C

G B

C D A

www.padeepz.net
www.padeepz.net
F D

G E F

E
A

B
C D

G E

II. Bi-Connectivity :

The vertices which are responsible for disconnection is called as


Articulation points.

If in a connected undirected graph, the removal of any node does not


affect the connectivities, then the graph is said to be biconnected graph.

1. Num Low(w) ≥ Num(v)


2. Low
Calculation of Num and Low gives the articulation point.

B A A (1,1)

B (2,1)

C D (3,1) C G (7,7)

www.padeepz.net
www.padeepz.net
F D (4,1)

G E E (5,4)

F (6,4)

BICONNECTIVITY :
A connected undirected graph is biconnective if there are no vertices
whose removal disconnects the rest of the graph.

A biconnected undirected graph is a connected graph that is not broken


into disconnected pieces by deleting any single vertex (and its incident
edges).
A biconnected directed graph is one such that for any two vertices v and
w there are two directed paths from v to w which have no vertices in
common other than v and w.
If a is not bio-connected,the vertices whose removal would disconnect
the graph is called articulation points.

DEFINITION

Equivalent definitions of a biconnected graph G:

Graph G has no separation edges and no separation vertices


For any two vertices u and v of G, there are two disjoint simple paths
between u and v (i.e., two simple paths between u and v that share no
other vertices or edges)
For any two vertices u and v of G, there is a simple cycle

containing u and v.

Biconnected Components

Biconnected component of a graph G are:

A maximal biconnected subgraph of G, or


A subgraph consisting of a separation edge of G and its end vertices

www.padeepz.net
www.padeepz.net
Interaction of biconnected components

An edge belongs to exactly one biconnected component


A nonseparation vertex belongs to exactly one biconnected component
A separation vertex belongs to two or more biconnected components

Articulation Point :

The vertices whose removal disconnects the graph are known as


Articulation Points.

Steps to find Articulation Points :

(i) Perform DFS, starting at any vertex.


(ii) Number the vertex as they are visited as Num(V).
(iii) Compute the lowest numbered vertex for every vertex V in the DFS
tree, which we call as low(W), that is reachable from V by taking one
or more tree edges and then possible one back edge by definition.

Low(V) = min(Num(V), Num(W), Low(W))

The Lowest Num(W) among all back edges V, W.

The Lowest Low(W) among all the tree edges V, W.

The root is an articulation if and only if (iff) it has more than two children.

Any vertex V other than the root is an Articulation point iff V has some child W
such that Low(W)≥Num (V)

A (1,1)

B (2,1)

C (3,1)

D (4,1) G (7,7)

www.padeepz.net
www.padeepz.net
E (5,4)

F (6,4)

Low(F) = min(Num(V), Num(W), Low(W))

= min(6, 4, -1)

=4

Low(E) = min(5, 6, 4)

=4

Low(D) = min(4, 1, 4)

=1

Low(G) = min(7, -, -)

=7

Low(C) = min(3, (4,7), (1,7))

=1

Low(B) = min(2, 3, 1)

=1

Low(A) = min(1, 2, 1)

=1

Example 2

B E H I

www.padeepz.net
www.padeepz.net

A C F I K

D
G

A F

D G E

I
Visited Parent[]
1 2 3 4
1 1 1 1 1 1 1 1
A B C D 0 1 2 3
0 1 2 3
1 1 1 1
Num[] A B C D

A A (1,1)

B C B (2,1)

D C (3,1)

www.padeepz.net
www.padeepz.net
D (4,4)

ALGORITHM

Routine to assign Num to Vertices

void AssignNum(Vertex V)
{
Vertex W;
int counter = 0;
Num[V] = ++counter;
visited[V] = True;
for each W adjacent to V
if(!visited[W])
{
parent[W] = V;
AssignNum(W);
}
}

Routine to compute low and to test for points

void AssignLow(Vertex V)
{
Vertex W;
Low[V] = Num[V]; /* Rule 1 */
for each W adjacent to V
{
if(Num[W] > Num[V]) /* forward edge or free edge */
{ AssignLow(W)
if(low[W] >= Num[V])
printf(“%v Articulation point is”, V);
Low[V] = min(Low[V], Low[W]); /* Rule 3 */
}
else
{
if(parent[V]! = W) /* Back edge */
Low[V] = min(Low[V], Num[W]); /* Rule 2 */

www.padeepz.net
www.padeepz.net
}
}
}

APPLICATION

Bio-Connectivity is a application of depth first search.


Used mainly in network concepts.

BICONNECTIVITY ADVANTAGES

Total time to perform traversal is minimum.


Adjacency lists are used
Traversal is given by O(E+V).

DISADVANTAGES

Have to be careful to avoid cycles


Vertices should be carefully removed as it affects the rest of the graph.

EULER CIRCUIT
EULERIAN PATH

An Eulerian path in an undirected graph is a path that uses each edge


exactly once. If such a path exists, the graph is called traversable or semi-
eulerian.

EULERIAN CIRCUIT

An Eulerian circuit or Euler tour in an undirected graph is a cycle that


uses each edge exactly once. If such a cycle exists, the graph is called

www.padeepz.net
www.padeepz.net
Unicursal. While such graphs are Eulerian graphs, not every Eulerian graph
possesses an Eulerian cycle.

EULER'S THEOREM

Euler's theorem 1

If a graph has any vertex of odd degree then it cannot have an Euler
circuit.
If a graph is connected and every vertex is of even degree, then it at least
has one Euler circuit.

Euler's theorem 2

If a graph has more than two vertices of odd degree then it cannot have
an Euler path.
If a graph is connected and has just two vertices of odd degree, then it at
least has one Euler path. Any such path must start at one of the odd-
vertices and end at the other odd vertex.

ALGORITHM

Fleury's Algorithm for finding an Euler Circuit

1. Check to make sure that the graph is connected and all vertices are of
even degree
2. Start at any vertex
3. Travel through an edge:
o If it is not a bridge for the untraveled part, or
o there is no other alternative
4. Label the edges in the order in which you travel them.
5. When you cannot travel any more, stop.

www.padeepz.net
www.padeepz.net
Fleury's Algorithm

1. pick any vertex to start .


2. from that vertex pick an edge to traverse .
3. darken that edge, as a reminder that you can't traverse it again .
4. travel that edge, coming to the next vertex .
5. repeat 2-4 until all edges have been traversed, and you are back at the
starting vertex .

At each stage of the algorithm:

the original graph minus the darkened (already used) edges = reduced
graph
important rule: never cross a bridge of the reduced graph unless there is
no other choice

Note:

the same algorithm works for Euler paths


before starting, use Euler’s theorems to check that the graph has an
Euler path and/or circuit to find.

APPLICATION

Eulerian paths are being used in bioinformatics to reconstruct the DNA


SEQUENCE from its fragments.

www.padeepz.net
www.padeepz.net
IMPORTANT SUMS

1. Topological Sort

V2 V3 VerticesIndegree
V1 0
V2 1 0
V3 1 0 0
V1 V4 V5 V6 V10 V4 1 0
V5 1 0
V6 2 1 0
V7 V8 V9 V7 2 1
0
V8 1 0
V9 1 0
V10 1 0
Enqueue V1 V2 V4 V3 V5 V10 V6
V9 V8 V7
Sorted Vertices : Dequeue V1 V2 V4 V3 V5 V10 V6
V9 V8 V7
V1 V2 V4 V3 V5 V10 V6 V9 V8 V7

www.padeepz.net
www.padeepz.net
b c
2

a d
6
6 4
f e

5. Write the pseudo code for Sorting algorithms

Pseudo Code for Topological Sort :

void Topsort(Graph G)

Queue Q;

vertex v,w; int counter = 0;

Q = Create Queue (Num Vertex);

Make Empty(Q);

for each vertex V

if (Indegree[V]==0)

enqueue(V,Q);

while(!Isempty(Q))

V = Dequeue(Q);

Topnum[V]=++Counter;

for each w adjacent to V

www.padeepz.net
www.padeepz.net
if(--Indegree[w]==0)

Enqueue(w,0);

if(counter!=Num Vertex)

Error(“Graph has a cycle”);

Dispose Queue(Q);

Pseudo Code to Perform Unweighted Sort :

void unweighted(Table T)

Queue Q;

Vertex v,w;

Q = Create Queue(Num Vertex);

Make Empty(Q);

while(!IsEmpty(Q))

V = Dequeue(o);

T[V].Known = True;

for each w adjacent to v

if(!T[w].Known)

www.padeepz.net

You might also like