Sunteți pe pagina 1din 8

DS DSAA (Common Topics )

6. Graphs
Graph is a non-linear data structure. It holds multiple elements (called as Vertices)
and these vertices are connected to each other by links (called as Edges).
Definition : A Graph consists of set of Nodes (or Vertices) and a set of links
connecting the two nodes called Arcs (or Edges).
G = ( V, E ) V Vertices, E Edges
They differ from other data structures in one major concept: each node may have
multiple successors as well as multiple predecessors.
To represent the complex data like networks we use Graphs.
They can be used to solve complex routing problems such as designing and routing
airlines among the airports they serve.

Some Terms used with Graphs :


A graph can be directed or undirected. An Undirected graph is a graph whose
edges dont have directions. The edges are considered to be rather bidirectional. An
undirected graph is shown in the figure (a) below. The set of nodes is { A, B, C, D, E,
F }. The edge (A,B) is same as edge (B,A). Thus, the set of edges is,
{ (A,B), (B,A), (B,E), (E,B), (C,E), (E,C), (E,F), (F,E), (C,F), (F,C), (C,D), (D,C),
(A,C), (C,A) }
A Directed graph (or Digraph) is a graph in which each edge has a direction to its
successor. The arrows between the two nodes represent arcs. Fig. (b) below shows a
directed graph. The set of arcs for the graph is,
{ <A,B>, <B,E>, <E,F>, <C,F>, <C,E>, <C,D><C,A> }

A
B

Fig. a
Fig. b
Two vertices are said to be Adjacent Vertices (or neighbours) if there their exists
an edge that directly connects them. In fig. a vertex A and B are adjacent to each
other, where as in fig. b, vertex B is adjacent to A, but B is not adjacent to A.
A Cycle is a path consisting of at least three vertices that starts and ends with the
same vertex. In Fig. (a) above A, B, E, C, A is a cycle and even the links between C,
E, F also form a cycle. Note, that the same vertices in digraph of fig. b, do not form
a cycle. A Loop is a special type of cycle in which a single edge (or arc) starts and
ends on the same vertex.
Two vertices are said to be connected if there is path between them. A graph is said
to be Connected if, suppressing the directions, there is a path from any vertex to
any other vertex in a graph. A directed graph is Strongly connected if there is path
from each vertex to every other vertex in the graph. A directed graph is Weakly
connected if there are at least two vertices that are not connected.
Prepared by, Santosh Kabir.
Mobile : 98336 29398

Pg 1of 8

Graphs
www.santoshkabirsir.com

DS DSAA (Common Topics )


Fig. (a) below shows a weakly connected graph, and fig. (b) shows a strongly
connected graph.

Fig. a
Fig. b
Degree of a vertex is a number of edges incident to it. In above fig. (b) degree of
vertex E is 3 and degree of vertex C is 4. The Outdgree of a vertex in a directed
graph is a number of arcs leaving the vertex; the Indgree of a vertex is a number of
arcs entering the vertex.

Graph Representations:
To represent a graph we need to store two sets. One set for vertices of a graph and a
second to represent the edges. The most common structures used to represent
graph are 1)Two-dimensional array and 2) Linked lists.

1) Adjacency Matrix:
Adjacency matrix is a two dimensional array of size N x N, where N in a number of
Vertices in a graph. The array element ( i , j ) holds value true if there is edge
existing between the ith and jth node, for a undirected graph, or an arc exists from ith
to jth node, in a digraph, else the element holds false. One can even use values 1 or
0 at the place of true or false.
( In case of weighted graphs, every (i, j)th element of the matrix holds the weight for
edge i,j or infinity (large value) to indicate absence of edge).
The two types of graphs and their Adjacency matrices are shown below,

A
B

Fig. a

A B

Prepared by, Santosh Kabir.


Mobile : 98336 29398

A
B
Pg 2of 8
C
D
E
F

0
0
1
0
0
0

C D

1
0
0
0
0
0

Fig. b

0 0 0 0
0 0 1 0
Graphs
0 1 1 1
www.santoshkabirsir.com
0 0 0 0
0 0 0 1
0 0 0 0

DS DSAA (Common Topics )


A B

A
B
C
D
E
F

0
1
1
0
0
0

1
0
0
0
1
0

E F

1
0
0
1
1
1

0
0
1
0
0
0

0
1
1
0
0
1

0
0
1
0
1
0

2) Adjacency List:
Adjacency list uses multiple linked lists to represent the given graph. A vertex
linked list or header node linked list in which each node holds vertex number and
information in the vertex of a given graph and two pointers. One pointer is used to
form a link between all the vertices of a graph and the other pointer works like
header or root of another linked list that holds vertex information that are
connected to the current vertex. Figure below shows adjacency list for digraph of
fig. (b) above.
For example the horizontal linked list starting from vertex C indicate that vertex C
has links to Vertices A, D, E and F.
A

E
/

Graph Traversals:
We have worked with the traversals of structures such as lists or binary trees.
These structures have a root node from where the traversals can start. In case of
graphs the traversals can be started from any node of a graph. Depending upon
sequence in which the nodes are visited there are two types of graph traversals.
Breadth-first traversal and Depth-first traversal.

1) Breadth-First traversal: ( Or Breadth First Search BFS)


In this traversal technique, all adjacent vertices of a vertex are processed before
going for the next level. We begin by picking up a starting vertex and after
processing it, we process all its adjacent vertices. When all the adjacent vertices are
processed, we pick up the first adjacent vertex and process all its adjacent vertices,
then the second adjacent vertex and so forth.
Prepared by, Santosh Kabir.
Mobile : 98336 29398

Pg 3of 8

Graphs
www.santoshkabirsir.com

DS DSAA (Common Topics )


The algorithm work as follows,
1. Create an empty queue (FIFO list) to hold vertices of a graph.
2. Insert the first vertex into a queue.
3. While queue is not empty repeat following..
a. Read (remove) front vertex from queue and process it.
b. Insert all its adjacent vertices that are not visited or not en-queued.
4. Go to 3

Lets apply above steps to the following graph with 6 vertices, starting at vertex A.

A
B

Steps performed
Keep vertex A in queue

Queue contents
A

Process A

B C

Process B

C E

Process C

E D F

Process E

D F

Process D

The newly added


nodes in each step are
shown with bold letters.

Process F
Thus, in BFT the nodes of the above graph will be traversed as follows,
A B C E D F

2) Depth-First traversal: (DFS )


In this traversal technique, all of a vertexs descendent vertices are processed before
we move on to an adjacent vertex. We begin by picking up a starting vertex and
after processing it, we select any adjacent vertex to the first vertex and process it.
Again we process any of second one till no vertex adjacent to it is left for processing.
The algorithm work as follows,
1. Create an empty stack (LIFO list) to hold vertices of a graph.
2. Push the first vertex on a stack
3. While stack is not empty repeat following..
Prepared by, Santosh Kabir.
Mobile : 98336 29398

Pg 4of 8

Graphs
www.santoshkabirsir.com

DS DSAA (Common Topics )


a. Pop (remove) top vertex from stack and process it.
b. Push all its adjacent vertices that are not considered previously.
4. Go to 3
5.

Lets apply above steps to the following graph with 6 vertices, starting at vertex A.

A
B

Steps performed

Stack Contents
A

Push A on stack

Bottom of the stack

C B

Pop & Process A, Push B, C

F E D B

Pop & process C , push F, E, D


Pop & Process F

E D B

Pop & Process E

D B

Pop & Process D

Pop & Process B


Newly pushed vertices are shown with bold letters in above figure.
DFT visits the nodes in following order,
A C F E D B

Functions and main() for Graph DFS, BFS :


void InputMatrix(int m[10][10], int n )
{
int i,j;
printf("\nEnter %d x %d Matrix\n\n", n , n);
for(i=0; i<n; i++)
{
printf("Row %d : \n" , (i+1) );

for( j=0; j<n; j++)


{
printf("Edge(%c, %c) :", (char)('A' + i),(char)('A' + j) );
Prepared by, Santosh Kabir.
Mobile : 98336 29398

Pg 5of 8

Graphs
www.santoshkabirsir.com

DS DSAA (Common Topics )


scanf("%d", &m[i][j]);
m[j][i] = m[i][j];
}
}
}
void DFS(int A[10][10], int n )
{
int i, v ;
int processed[10]; // holds 1 for processed Vertex
// initialize all processed = 0

for(i=0; i<n; i++ )


processed[i] = 0;
// Initialize empty stack

stak.top = -1;
v = 0;
// first vertex (i.e. A)
processed[v] = 1;
Push( v );
while( ! IsStackEmpty() )
{
v = Pop();
printf( "%c\t" , (char)('A' + v ));
for( i=0; i<n; i++ )
{
if( A[v][i] == 1 && !processed[i]
{
Push( i );
processed[ i ] = 1;
}
}
}

These notes are also available at :


www.santoshkabirsir.com
void BFS( int A[10][10], int n )
{
int v, i ;
Prepared by, Santosh Kabir.
Mobile : 98336 29398

Pg 6of 8

Graphs
www.santoshkabirsir.com

DS DSAA (Common Topics )


int processed[10];
for(i=0; i<n; i++ )
processed[i] = 0;
// Initialize empty Q

q.fe=q.re = -1;
v = 0; // first vertex (i.e. A)
processed[v] = 1;
Add( v );
while( ! IsQEmpty() )
{
v = Remove();
printf( "%c\t", (char)('A' + v));
for( i=0; i< n; i++ )
{
if( A[v][i] == 1 && !processed[i]
{
Add( i );
processed[ i ] = 1;
}
}
}

}
void main( )
{
int A[10][10];
// Adjacency matrix
int n; // no. of vertices
int opt;
while( 1 )
{
printf("\nInput Matrix ...1\n");
printf("DFS ............2\n");
printf("BFS ............3\n");
printf("Quit ...........4\n");
printf("Enter option: ");
scanf("%d", &opt);
switch( opt )
{
case 1:
printf("\nEnter number of vertices (max 10) :");
scanf("%d", &n);
InputMatrix( A, n );
break;
case 2:
printf("\nDepth First Search ...\n");
DFS( A, n );
Prepared by, Santosh Kabir.
Mobile : 98336 29398

Pg 7of 8

Graphs
www.santoshkabirsir.com

DS DSAA (Common Topics )


break;
case 3:
printf("\nBreadth First Search ...\n");
BFS( A, n );
break;
case 4:
return;
}
}
getch();
}

Note :
Some more topics of Graphs for IT branch in separate notes.
------0000------

Sem IV - IT

Web Programming ( WP )
[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]

( Learn to design and develop small Internet based programs )


Regular Batches will start in 10 days after Sem III
Exams

ANDHERI, DADAR , THANE

Santosh Kabir sir


Mobile : 98336 29398
www.santoshkabirsir.com

Prepared by, Santosh Kabir.


Mobile : 98336 29398

Pg 8of 8

Graphs
www.santoshkabirsir.com

S-ar putea să vă placă și