0% found this document useful (0 votes)
10 views14 pages

DS Unit-5

This document provides an overview of graphs as a nonlinear data structure consisting of vertices and edges, detailing various types of graphs such as directed, undirected, and weighted graphs. It covers key concepts including graph terminology, representation methods, spanning trees, and traversal techniques like Depth First Search (DFS) and Breadth First Search (BFS). Additionally, it discusses practical applications of graphs in fields such as social networking, navigation systems, and computer networking.

Uploaded by

ksuryatheja2002
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)
10 views14 pages

DS Unit-5

This document provides an overview of graphs as a nonlinear data structure consisting of vertices and edges, detailing various types of graphs such as directed, undirected, and weighted graphs. It covers key concepts including graph terminology, representation methods, spanning trees, and traversal techniques like Depth First Search (DFS) and Breadth First Search (BFS). Additionally, it discusses practical applications of graphs in fields such as social networking, navigation systems, and computer networking.

Uploaded by

ksuryatheja2002
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/ 14

Data Structures Unit - V

GRAPHS
Graph:
Graph is a nonlinear data structure; it contains a set of points known as nodes (or vertices) and set of
links known as edges (or Arcs) which connects the vertices. A graph, is defined as follows... A graph, G
consists of two sets V & E. V is a finite non-empty set of vertices. E is a set of pairs of vertices, these pairs are
called edges.
E.g.:
A
C

B D

Graph Terminology:
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.
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).
E.g. The link between vertices A and B is represented as (A, B). There are 7 edges in the
graph (i.e., (A, B), (A, C), (A, D), (B, D), (B, E), (C, D), (D, E)).
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).
3.Weighted Edge - A weighted edge is an edge with cost on it
Directed Graph:
If the pair of nodes that make up the arcs are ordered pairs the graph is said to be a directed graph.
Or a graph in which all the edges are directed is called as Directed graph or a Digraph i.e., each edge is
represented by a directed pair and denoted as (v1, v2) where v1 is the starting vertex and v2 the ending vertex
of the edge. Eg:

Vertices ={ A, B, C, D, E, F}
Edges={(A, B), (B, C), (C, E), (E, F), (E, D), (D, B)}
Department of Computer Science, SSBN Degree College, ATP
1

Data Structures Unit - V


Undirected Graph:
An undirected graph is a graph in which the pair of vertices is a representing any edge is unordered.
Or a graph in which all the edges are unordered is called as Un directed graph. Thus, the pairs (v1, v2) and
(v2, v1) represented the same edge.

Eg:

Vertices= {A, B, C, D, E}
Edges = {{A, B}, {A, D}, {A. E}, {B, E}, {B, D}, {D, C}}

Weighted Graph:
A graph in which a number is associated with each arc is called a weighted graph or network.
E.g.

90
20

BC
60

Degree:
Total number of edges connected to a vertex is said to be degree of that vertex.
In degree
Total number of incoming edges connected to a vertex is said to be in degree of that
vertex. Out degree
Total number of outgoing edges connected to a vertex is said to be out degree of that
vertex. Parallel edges or Multi 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 the starting vertex and ending vertex is the same
vertex. Simple Graph
A graph is said to be simple if there are no parallel and self-loop edges.
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.

Department of Computer Science, SSBN Degree College, ATP


2
Data Structures Unit - V

Path:

A path of length ‘k’ from node ‘a’ to node ‘b’ is defined as a sequence of ‘KH’ nodes. n1, n2,….nk+1

such that n1=A, nk+1=B and adjacent (ni, ni+1) is true for all i between 1 and k.
Note:
»A path from a node to itself is called a cycle and a graph containing it is called cyclic.
»A graph with at least one cycle is called as cyclic graph.
»A graph without cycles is called as acyclic graph.
Representation of Graph:
A graph can be represented in two ways in memory. One is sequential representation by means of
matrix called adjacency matrix, the other way is linked representation by means of linked lists. Sequential
representation:
A graph is conveniently represented by a matrix (two-dimensional array) called adjacency matrix. A
graph containing n nodes can be represented by a matrix containing n rows and n columns.

Adjacency Matrix:
Let us suppose ‘G’ is a simple directed graph with ‘m’ nodes and suppose the nodes of G have been
ordered and are named v1,v2,….vm then the adjacency matrix A={aij} of the graph ‘G’ is the mxm matrix
defined as

aij = 1 if vi is adjacent to vj i.e., if there is edge from vi to vj. Other wise 0


E.g.

Note:
» If the graph is an undirected graph then the adjacency matrix is symmetric.

Disadvantages:
» Graphs with few edges would have a lot of wasteful zeros in the adjacency matrix i.e., the
corresponding adjacency matrix is sparse
» Insertion & deletion of nodes is difficult
Department of Computer Science, SSBN Degree College, ATP
3

Data Structures Unit - V


Linked representation:
In this representation two different types of linked lists are used. One to maintain all the vertices in
the graph called as Node list and another to maintain all the edges in the graph called as Edge list or
Adjacency List. In node list, each node corresponds to a Vertex in graph G, & it contains the following 3
fields.

class Node
{
String data;
Data Next Adjacent
Node next;
Edge adjacent;
}

Where
» Data – holds the value of associated with the vertex in the graph
» Next – address field that points to next vertex in the node list
» Adjacent – address field that points to the first node of adjacency list of the node.

In Edge List, each node corresponds to an edge of graph G A node in the edge list contain two or three fields.

class Edge
{
Terminal Pointer Weight
Node terminal;
Edge pointer;
double weight;
}

Where
» Terminal – address field that points to node in the node list which is terminal vertex of the edge in the
graph
» Pointer –Address field that points to next node in the adjacency list which are all initiated from same
Vertex in the graph

Consider the following directed graph & form the adjacent list of the graph.

Department of Computer Science, SSBN Degree College, ATP


4
Data Structures Unit - V

Applications of Graphs:
Most of the real-world problems can be represented by using Graphs with the help of standard algorithms
most problems can be solved

• Social Networking (Facebook): Each user is represented as a vertex and two people are friends when
there is an edge between two vertices. Similarly, friend suggestion also uses graph theory concept. •
Navigation Systems (Google Maps): Various locations are represented as vertices and the roads are
represented as edges and graph theory is used to find shortest path between two nodes. •
Recommendations on e-commerce websites (Amazon, Flipkart): 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 theory is used in design of the circuits in electronics.
• Transportation network (highways, railway lanes etc.,).
• In World Wide Web, web pages are considered to be the vertices. There is an edge from a page u to
other page v if there is a link of page v on page u. This is an example of Directed graph. It was the
basic idea behind Google Page Ranking Algorithm.

• In computer network, the relationships among interconnected computers within the network, follow
the principles of graph theory.

Finding Path between two nodes:


Let G be a graph with the cities as nodes and the roads as arcs. The problem is to determine whether
there is a path of required length by which one can travel from the first of the given cities to the second. To
find a path of length nr from node A to node B, look for a node C such that an arc exists from A to C and a
path of length nr – 1 exists from C to B. If these conditions are satisfied for some node C, the desired path
exists. If the conditions are not satisfied for any node C, the desired path does not exist.
The algorithm uses an auxiliary recursive function Findpath (k, a, b). This function returns true if there
is a path of length k from A to B and otherwise false is returned. The graph is represented as Adjacent
matrix, using a two-dimensional boolean array Adj [] []. The algorithm also uses a function adjacent () which
accepts two nodes and return true if they are adjacent otherwise false is returned
E.g.:
H

GC
B

Path from A to B: - A – C – G – B

E F A D
Department of Computer Science, SSBN Degree College, ATP
5

Data Structures Unit - V


Algorithm to find the path between two nodes:
boolean Findpath (k, a, b)
{
if (k==1) // search for a path of length 1
return (adjacent (a, b));
// determine if there is a path through c
for (c=0; c < n; c++)
if (adjacent (a, c) && findpath (k-1, c, b))
return (true);
return(false);
}
boolean adjacent (int node1, int node2)
{
return (Adj[node1] [node2] ==true)? true: false);
}
Spanning Tree:
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible
number of edges. Hence, a spanning tree does not have cycles and it cannot be disconnected.
In simple terms every connected and undirected Graph G has at least one spanning tree. A disconnected
graph does not have any spanning tree, as it cannot be spanned to all its vertices. A complete undirected
graph can have maximum nn-2 number of spanning trees, where n is the number of nodes. The spanning
trees of a graph are collectively called as Spanning forest.
Spanning Forest:
A graph G is given, F is a spanning forest of G if
1. F is a sub graph of G containing all nodes of G.

2. F is an ordered forest containing trees T1, T2 , T3,.. . Tn.

3. Ti contain all nodes that are reachable from the root of Tj and are not contained in Ti i.e., j<i.

Graph G

B C

Spanning Trees
A
A
A

BC
BC
BC

Department of Computer Science, SSBN Degree College, ATP


6
Data Structures Unit - V

Properties of Spanning Trees:


» A connected graph G can have more than one spanning tree.
» All possible spanning trees of graph G, have the same number of edges and vertices.
» The spanning tree does not have any cycle (loops).
» Removing one edge from the spanning tree will make the graph disconnected, i.e., the spanning tree is
minimally connected.
» Adding one edge to the spanning tree will create a circuit or loop, i.e., the spanning tree is maximally
acyclic.
» Spanning tree has n-1 edges, where n is the number of nodes (vertices).
» From a complete graph, by removing maximum e - n + 1 edges, we can construct a spanning
tree. » A complete graph can have maximum nn-2 number of spanning trees.
Minimum Spanning Tree (MST):
In a weighted graph, a minimum spanning tree is a spanning tree that has minimum weight than all
other spanning trees of the same graph. In real-world situations, this weight can be measured as distance,
congestion, traffic load or any arbitrary value denoted to the edges.
Applications:
Spanning tree is basically used to find a minimum path to connect all nodes in a graph. Common application
of spanning trees includes
» Civil Network Planning (laying telephone lines etc.,)
» Computer Network Routing Protocol
» Cluster Analysis

Undirected Graph Traversal:


Graph traversal is technique used for searching a vertex in a graph. The graph traversal is also used to
decide the order of vertices to be visit in the search process. A graph traversal finds the edges to be used in
the search process without creating loops that means using graph traversal we visit all vertices of graph
without getting into looping path. There are two methods in graph traversal.
They are Depth First Traversal (DFS), Breadth First Traversal (BFS).

Depth first Traversal:


A depth first traversal as its name indicates traverses a single path of the graph as far as it can go. It
then resumes at the last node on the path just traversed that has an unvisited tree created by a depth first
traversal tend to be very deep. If every node in the graph is reachable from the starting node then the
spanning forest is a single spanning tree. There may be more than one depth first traversals and spanning
trees for a directed graph (because starting node can be chosen arbitrarily). This traversal mainly depends on
how the graph is represented and how the nodes are numbered as starting node and on the choice of
starting node and successors. The important feature of depth first traversal is that, after a node is visited all
descendants of the node are visited before its unvisited brothers. Depth first traversal uses a stack data
structure to perform traversing.
Department of Computer Science, SSBN Degree College, ATP
7

Data Structures Unit - V


DFS - A B C G F E D
Algorithm:
1. All nodes are initialized to ready state & initialize stack to empty
2. Begin with any node which is on ready state & push into stack mark the states of that node to
waiting 3. While stack is not empty do
Begin
a) Pop the top node k – of stack & process it. Mark the status of that node to visited
b) Push all the adjacent nodes of k which are in ready state into stack & mark the status of those
nodes to waiting
End
4. If the graph still contains nodes which are in ready state then go to step 3
5. Return
Efficiency:
The efficiency of both Depth First Traversal is quadratic order (O (V2)) of growth when the graph is
represented using adjacency matrix and O(V+E) when the graph is represented using adjacency list where v is
the number of vertices and E is number edges in the graph
Applications:
• For a weighted graph, DFS traversal of the graph produces the minimum spanning tree.
• Detecting cycle in a graph.

• Solving puzzles with only one solution, such as mazes.


• Using DFS we can find path between two given vertices u and v.

Breadth first Traversal:


This is just a contradiction to the depth first traversal. Here it visits all the successors of a visited node
before visiting any successors of those successors i.e., it visits the brothers of the visited node first and then
visits its successors whereas depth first traversal tends to create very long and narrow trees. Breadth first
traversal creator very wide trees. This traversal is implemented by using a queue representing the fact that
visiting the first node is the first whose successors are visited. This can be used to determine if a graph is
cyclic. This algorithm can be used to find the shortest path from one node to another. Breadth first traversal
uses a Queue data structure to perform traversing.

Department of Computer Science, SSBN Degree College, ATP


8
Data Structures Unit - V

BFS - A B E D C F G

Algorithm:
1. All nodes are initialized as ready states & initialize queue to empty
2. Begin with any node, which is in ready state & put into queue. Mark the states of that node to
waiting 3. while queue is not empty do
Begin
a) Delete the first node k from queue & process it. Mark the states of that node to visited b) Add
all the adjacent nodes of k which are in ready state to the rear side of the queue and mark the
states of those nodes to waiting
End
4. If the graph still contains nodes which are in ready state then go to step2
5. Return

Efficiency:
The efficiency of both Breadth First Traversal is quadratic order (O (V2)) of growth when the graph is
represented using adjacency matrix and O(V+E) when the graph is represented using adjacency list where v is
the number of vertices and E is number edges in the graph

Applications:
• In Peer-to-Peer Networks like BitTorrent, Breadth First Search is used to find all neighbor nodes.
• Crawlers in Search Engines: Crawlers build index using Breadth First

• Social Networking Websites: In social networks, we can find people within a given distance ‘k’ from a
person using Breadth First Search till ‘k’ levels.

• GPS Navigation systems: Breadth First Search is used to find all neighboring locations. • Broadcasting in
Network: In networks, a broadcasted packet follows Breadth First Search to reach all nodes.
Department of Computer Science, SSBN Degree College, ATP
9

You might also like