0% found this document useful (0 votes)
133 views17 pages

UNIT - IV (Graphs)

The document discusses different ways to represent graphs in data structures. It defines key graph terminology like nodes, edges, directed vs undirected graphs, and weighted graphs. It then describes three major approaches to represent graphs: adjacency matrix representation, adjacency list (linked) representation, and multilist representation. The bulk of the document focuses on adjacency matrix representation, providing examples of how to represent both directed and undirected graphs, as well as weighted graphs, using the adjacency matrix approach.

Uploaded by

varun MAJETI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views17 pages

UNIT - IV (Graphs)

The document discusses different ways to represent graphs in data structures. It defines key graph terminology like nodes, edges, directed vs undirected graphs, and weighted graphs. It then describes three major approaches to represent graphs: adjacency matrix representation, adjacency list (linked) representation, and multilist representation. The bulk of the document focuses on adjacency matrix representation, providing examples of how to represent both directed and undirected graphs, as well as weighted graphs, using the adjacency matrix approach.

Uploaded by

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

Data Structures Using Java UNIT-IV II Year IV Semester B.

Sc

GRAPHS

A graph is a set of nodes (or) vertices and edges (or) branches which connect
them. A graph can be represented as G=(V, E)
Where ‘V’ is the set of nodes and ‘E’ is the set of edges.

Fig. below shows a graph.


1

2 3

4 5 6 7

If two nodes are connected by an edge, those two nodes are said to be adjacent
(or) neighbors.

Ex: In above fig. the nodes adjacent to node 3 are 1,4,5 and that to node ‘2’ are 1,4.

undirected Graph:
The edge which has no specific direction is called undirected edge. The graph
with undirected edges is called a undirected graph. The graph shown in the above
fig. is a undirected graph.

Directed Graph:
An edge, which has direction, is called directed edge. Direct edge is
unidirectional. It goes from one node to another.

A directed graph (or) digraph is a graph in which all edges are directed edges.
Fig. below shows the directed graph.

A
B

C D
All edges in the above graph are directed. Directed edges are unidirectional .
Ex: There is a edge B to C, but there is no edge representing the reverse relationship.

A graph contains both directed and undirected edges is called mixed graph.

Department of Computer Science 1 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

If a node does not have any adjacent nodes, then it is said to be isolated node.

Ex:
A

B C D
‘D’ is isolated node.

Null Graph:

A graph which contains only isolated nodes is called a Null Graph.

Loop:
An edge in a graph which starts and ends on the same node is called a loop. A
loop can be considered either a directed (or) undirected.

Ex:

C
B D
Multigraph:

A pair of nodes may be connected by more than one edge. Such edges are
referred to as parallel. A graph with parallel edges is called multigraph. A simple
graph is a graph in which there are no parallel edges.

Path :
A path P of length n from node u to a node v is defined as sequence of n+1
nodes.
P=(v0,v1,v2,….vn)
where u=v0 and v=vn .
The path P is said to be closed if v0 = vn
The path P is said to be simple if all the nodes except first and last are different.

Cycle: a cycle is a closed simple path with length 3 or more. A cycle of length k is
called
k-cycle.

Department of Computer Science 2 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

Connected graph:
a graph G is said to be connected if there is a path between any two of its nodes.

Complete graph:
a graph G is said to be complete if every node u in G is adjacent to every other node
v in G. A complete graph with n nodes will have n(n-1)/2 edges. A complete directed
graph with n nodes require n(n-1) directed edges.

Tree graph: a connected graph with out any cycles is called tree graph.

Sub graph: a graph H is a subgraph of another graph G, iff its vertex and edge sets
are subsets of those of G.
Spanning tree : A sub graph of G that contains all vertices of G, that contains no
cycle is called spanning tree of G.
Degree of a Node:
The degree of a node is the number of edges connected directed to that node
i.e. the number of edges incident on it.

In a directed graph, the indegree of a node is the number of edges coming into
the node. The outdegree of a node is the number of edges leaving the node. The sum
of indegree and outdegree of a particular node is called total degree of that node. In
case of undirected graphs, total degree is nothing but degree itself. The concept of
indegree and outdegree can not apply to undirected graph. A node whose indegree
is ‘0’ is called a source node and a node whose outdegree is ‘0’ is called sink node.

Ex: A C

B
E
For Node ‘B’: D For Node E:
In degree : 2 In degree: 2
Outdegree: 2 Out degree: 1
Total degree: 4 Total degree: 3

Weighted graph:

A weighted graph is a graph that has a weight associated with each edge.
Fig. below shows the weighted graph.

B
4 5

Department of Computer Science 3 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

6
A C

8
7 15

D 9 E

Representation of Graphs
There are three major approaches to represent graphs.
i. Adjacency Matrix representation.
ii. Adjacency list representation (or) linked representation.
iii. Multilist representation.

Adjacency Matrix Representation:


Consider a graph G with set of nodes V(G) and set of edges E(G). If there are
‘N’ nodes in V(G), for N>=1, the graph ‘G’ may be represented by an adjacency
matrix which is a table with ‘N’ rows and ‘N’ columns where

A(i,j) = 1 if and only if there is an edge (Vi, Vj) in E(G).


= 0 if there is no edge.
If there is an edge connecting Vi and Vj in E(G), the value in the [i,j] position in
the table is 1, otherwise it is 0.
Ex: Consider the following graph which is a directed graph.

A C

B D

There are 4 nodes, therefore adjacency matrix of the above graph consists ‘4’
rows and ‘4’ columns.
A B C D
A 0 1 1 0

0 0 0 1
B
0 1 0 0
C

D
Department of Computer Science 4 A.S.N. Degree College, Tenali
Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

0 0 1 0

Adjacency Matrix representation of undirected graph:

Consider the following undirected graph.

C
A

Since each edge in the graph is undirected, there is a bi-directional relation


between nodes because of each edge. There are ‘4’ nodes in the graph, the adjacency
matrix of the graph consists ‘4’ rows and ‘4’ columns as shown in the fig. below.

A B C D
A 0 1 0 1

1 0 1 1
B
0 1 0 1
C
1 1 1 0
D

The adjacency matrix for an undirected graph is symmetric and for directed
graph need not be symmetric. The space needed to represent a graph using its
adjancy matrix is n2 bits. For an undirected graph the degree of any vertex is its row
sum. For directed graph ,the row sum is out degree and column sum is in degree.

Adjacency Matrix representation of Weighted graph:

Consider the following weighted graph.

B
1.5 2

A 3 D

Department of Computer Science 5 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

1 2.7
C

For weighted graph, the column, row intersection in matrix contains the
weight of that edge, otherwise it is ‘0’. The adjacency matrix of the graph is as shown
below.

A B C D
A 0 1.5 1 0

0 0 0 2
B
0 3 0 2.7
C
0 0 0 0
D

Adjacency list (or) linked representation of Graph:

The use of adjacency matrix to represent a graph is inadequate because of its


static implementation. If a graph is updated dynamically during program execution
to add (or) delete a node, the dimension of the array have to be changed, a new array
is to be created for each updation. The adjacency matrix requires storage for each
possible edge between each pair of nodes irrespective of the fact whether the edge
exist (or) not.

This disadvantages can be overcome if graph is represented using adjacency


list. The adjacency list stores information about only those edges that exist. The
adjacency list contains a directory and a set of linked lists.

The directory contains one entry for each node of the graph. Each entry in the
directory points to a linked list that represents the nodes that are connected to that
node. The directory represents nodes and the linked list represents the edges.

Each node of the linked list has three fields one is the node identifier, second is a link
to the next field and the third is an optional weight field which contains the weight of
the edge.

Node- ID Weight Next

Ex: Consider the following directed graph.

Department of Computer Science 6 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

1 3 5

4 6

Since No weights for edges the node of the linked list will be

Nodeid Next

The adjacency representation of the above graph is as shown below.

4
1

2 1 3 5

3 4

5 6
4

5
Department of Computer Science 7 A.S.N. Degree College, Tenali
6
Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

NULL

NULL

Ex : Consider the following weighted graph.


1
3 7
Node Structure

2 4 4 Nodeid Weight Next

8 1

3 5
6

1 2 3 3 4 4 7

2
3 8

3
4 1 5 6

4
NULL

5 NULL

* Un directed graphs can be stored using adjacency lists, however, each edge will be
represented twice, once in each direction.

Department of Computer Science 8 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

Graph Traversal

There are two methods for graph traversal.


1. Breadth-first traversal (BFS)
2. Depth-first traversal (DFS)

Breadth-first traversal:
Breadth-first search operates by processing nodes in layers. The breadth-first
search can begin at any arbitrary node. The nodes which are adjacent to the start
node are processed first, and proceeds to adjacent nodes of that nodes just visited.
This process continues until all the nodes are visited.

A data structure queue is used to place all waiting nodes i.e. nodes to be
visited. Following is the procedure for BFS.

1. All nodes are initialized as ready states and initialize queue to empty.
2. Begin with any node which is in ready state and put into queue. Mark the
status of that node to waiting.
3. While queue is not empty, repeat the following steps:
i. Delete the first node say ‘k’ from queue and process it. Mark the
status of that node to visited.
ii. Add all the adjacent nodes of K which are in ready state to the rear
side of the queue and mark the status of those nodes to waiting.
4. If the graph still contains nodes which are in ready state, then repeat the
process from step2.

Ex: Consider the following graph.

2 3

4 5 6 7

8
If starting node 1, then BFS result is

Department of Computer Science 9 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

1 2 3 4 5 6 7 8

Ex:
1

2 4

3 5

BFS result: 1 2 3 4 5

Depth-first Traversal:
The depth-first traversal of a graph is much similar to preorder traversal of an
ordered tree. The traversal of a graph may start at any arbitrary node, say A. If B, C,
D and E are the nodes adjacent to A. Then after A, B will be visited keeping C,D and
E is waiting. After visiting B, all the nodes adjacent to B will be visited before
returning to traverse C,D and E.
Data structure stack will be used to push all waiting nodes. Following is the
procedure for DFS.
1. All nodes are initialized to ready state and initialize stack to empty.
2. Begin with any node which is in ready state and push into stack. Mark the
status of that node to waiting.
3. While stack is not empty, repeat the following steps.
i. POP the top node, say ‘K’ and process it. Mark the status of that
node to visited.
ii. Push all the adjacent nodes of ‘K’ which are in ready state into stack
and mark the status of those nodes to waiting.
4. If the graph still contains nodes which are in ready state then, repeat the
process from step2.
Ex: Consider the following graph.

Department of Computer Science 10 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV 1 II Year IV Semester B.Sc

2 3

4 5 6 7

8
If starting node is 1, then DFS result is

1 2 5 8 4 3 7 6
(or)
1 3 7 8 6 2 5 4
Ex:
1

2 3

4 5

DFS result: 1 2 4 5 3
(or)
1 3 4 5 2

Department of Computer Science 11 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

Spanning Tree

Spanning tree can be defined as a sub-graph of connected, undirected graph G that is a


tree produced by removing the desired number of edges from a graph. In other words,
Spanning tree is a non-cyclic sub-graph of a connected and undirected graph G that
connects all the vertices together. A graph G can have multiple spanning trees.

Minimum Spanning Tree

There can be weights assigned to every edge in a weighted graph. However, A minimum
spanning tree is a spanning tree which has minimal total weight. In other words, minimum
spanning tree is the one which contains the least weight among all other spanning tree of
some particular graph.

Shortest path algorithms

In this section of the tutorial, we will discuss the algorithms to calculate the

shortest path between two nodes in a graph. There are two algorithms which are

being used for this purpose.

o Prim's Algorithm
o Kruskal's Algorithm

Prim's Algorithm

Prim's Algorithm is used to find the minimum spanning tree from a graph. Prim's
algorithm finds the subset of edges that includes every vertex of the graph such
that the sum of the weights of the edges can be minimized.

Prim's algorithm starts with the single node and explore all the adjacent nodes with all
the connecting edges at every step. The edges with the minimal weights causing no
cycles in the graph got selected.

The algorithm is given as follows.


Algorithm

o Step 1: Select a starting vertex


o Step 2: Repeat Steps 3 and 4 until there are fringe vertices
o Step 3: Select an edge e connecting the tree vertex and fringe vertex that has
minimum weight

Department of Computer Science 12 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

o Step 4: Add the selected edge and


the vertex to the minimum spanning
tree T [END OF LOOP]
o Step 5: EXIT

Example :
Construct a minimum spanning tree of the graph given in the following figure by using
prim's algorithm.

Solution

Step 1 : Choose a starting vertex B.


Step 2: Add the vertices that are adjacent to A. the edges that connecting the vertices are
shown by dotted lines
Step 3: Choose the edge with the minimum weight among all. i.e. BD and add it to MST.
Add the adjacent vertices of D i.e. C and E.
Step 3: Choose the edge with the minimum weight among all. In this case, the edges
DE and CD are such edges. Add them to MST and explore the adjacent of C i.e. E and
A.
Step 4: Choose the edge with the minimum weight i.e. CA. We can't choose CE as it would
cause cycle in the graph.
The graph produces in the step 4 is the minimum spanning tree

of the graph shown in the above figure. The cost of MST will be

calculated as;

cost(MST) = 4 + 2 + 1 + 3 = 10 units.

Department of Computer Science 13 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

Kruskal's Algorithm

Kruskal's Algorithm is used to find the minimum spanning tree for a connected
weighted graph. The main target of the algorithm is to find the subset of edges by
using which, we can traverse every vertex of the graph. Kruskal's algorithm follows
greedy approach which finds an optimum solution at every stage instead of focusing
on a global optimum.

The Kruskal's algorithm is given as follows.

Algorithm

o Step 1: Create a forest in such a way that each graph is a separate tree.
o Step 2: Create a priority queue Q that contains all the edges of the graph.
o Step 3: Repeat Steps 4 and 5 while Q is NOT EMPTY
o Step 4: Remove an edge from Q
o Step 5: IF the edge obtained in Step 4 connects two different trees, then Add it
to the forest (for combining two trees into one tree).

Department of Computer Science 14 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

ELSE
Discard the edge
o Step 6: END

Example :

Apply the Kruskal's algorithm on the graph given as follows.

Solution:

Department of Computer Science 15 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

Department of Computer Science 16 A.S.N. Degree College, Tenali


Data Structures Using Java UNIT-IV II Year IV Semester B.Sc

Department of Computer Science 17 A.S.N. Degree College, Tenali

You might also like