0% found this document useful (0 votes)
5 views42 pages

Ads 5 Graph

Unit 5 covers the fundamentals of graphs, including definitions, types, and representations such as adjacency matrices and lists. It introduces graph traversal algorithms like Depth First Search (DFS) and Breadth First Search (BFS), along with their applications in various fields. The unit also discusses graph terminologies and provides C programming examples for implementing graph traversal techniques.

Uploaded by

krishnasahu2853
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)
5 views42 pages

Ads 5 Graph

Unit 5 covers the fundamentals of graphs, including definitions, types, and representations such as adjacency matrices and lists. It introduces graph traversal algorithms like Depth First Search (DFS) and Breadth First Search (BFS), along with their applications in various fields. The unit also discusses graph terminologies and provides C programming examples for implementing graph traversal techniques.

Uploaded by

krishnasahu2853
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/ 42

TechnoScan - Unit - 5 1

Unit-5

Graph

Syllabus
Graphs: Concepts and terminology, Representation of graphs using adjacency matrix,
adjacency list, Depth First search and Breadth First Search Algorithms, Spanning trees,
Minimal cost spanning tree and Shortest path algorithm ( Single Source-all pairs).

Introduction: The vast majority of computer algorithm operates on data. Organsing these data in
a certain way (i.e. data structure) has a significant role is design and analysis of algorithm. Graph is
one such fundamental data structure. Array, linked list, stack, queue, tree, sets are other important
data structures. A graph is generally used to represent connectivity information i.e. connectivity
between cities for example. Graphs have been used and considered very interesting data structures
with a large number of applications for example the shortest path problem. While several
representations of a graph are possible, we discuss in the unit the two most common representations
of a graph: adjacency matrix and adjacency list and also adjacency multilist. Many graph algorithms
requires visiting nodes and vertices of a graph. This kind of operation is also called traversal. You
must have read various traversal methods for tree such as preorder. postorder and inorder. In this
unit we present two graph traversal algorithms which are called as Depth first search and Breadth
first search algorithm.

Definition of graph:

• A graph is a nonlinear Data Structure.


• A graph G consists of two properties:
• A set V of elements called vertices or nodes.
• A set E of connectors called edges.
• G (V, E) represents a graph.
• The order of a graph is |V| (the number of vertices).
• A graph's size is |E|, the number of edges.
• A tree is a graph with no cycle.
2 Algorithms and Data Structures

Example1: A Graph G1:

Figure1: Graph G1
• In Graph G1 consists:
• 4 Vertices V(G1) : {0, 1, 2, 3}
• 6 Edges E(G1) : {(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)}

Example2: A Graph G2:

Figure2: Graph G2 (Undirected graph)


• In Graph G2 consists:
• 5 Vertices V(G2) : {A, B, C, D, E}
• 6 Edges E(G2) : {(A,B), (A,C), (B,D),(B,E), (C,D), (D,E)}

Different types of graph:

• Directed graph: A directed graph G = (V, E) consists of a set V of vertices and a set E of
edges that are ordered pairs of elements in V.

• Each edge in a graph has a direction


• For each eE, e = (u, v) where u, vV.
• In directed graph (u, v) != (v, u). (Not Equal to)
• An edge e is a loop if e = (u, u) for some uV.
TechnoScan - Unit - 5 3

Example:

Figure3: Graph G (Directed graph)


• In Graph G consists:
• 4 Vertices V(G) : {A, B, C, D}
• 5 Edges E(G) : {<A,B>, <A,C>, <C,B>,<C,D>, <D,B>}

• Connected Graph: A graph G (V, E) is called connected if there is a simple path between
any two of its nodes.
Example:

Figure4: Connected Graph

• Complete Graph: A graph G (V, E) is complete if every node in graph G is adjacent to


every other node. A complete graph with n nodes will have n(n-1)/2 edges.
Example:

Figure5: Complete Graph


4 Algorithms and Data Structures

• Labeled Graph: A graph G (V, E) is said to be labeled if its each edges are assigned a
label.
Example:

Figure6: Labeled Graph

• Weighted Graph: A weighted graph G (V, E) is labeled graph where each edge is assigned
a nonnegative numerical value w (e).
Example:

Figure7: Weighted Graph

• Tree Graph: A Tree graph G (V, E) is a connected graph with no cycle. If a tree graph has
m nodes, then there are m-1 edges.
Example:

Figure8: Tree Graph


TechnoScan - Unit - 5 5

• Multigraph: A graph G (V, E) is a multigraph which has the following properties:


(a) Multiple Edges
(b) Loops
Example:

Figure9: MultiGraph

Graph terminologies:
• Number of edges:
• For undirected graph with n vertices, the maximum number of edges is n(n-1)/2.
• For directed graph with n vertices, the maximum number of edges is n(n-1)
• Isolated Node: A vertex u with no edges.
• Path: A path P of length n from a node u to node v is defined as a sequence n+1 nodes
such that P= (v0, v1, ….vn).
(a) Simple Path: if all nodes in path P are distinct.
(b) Closed Path: If node v0 = vn.
• Cycle: A closed path, with no other repeated vertices other than the starting and the
ending vertices.
Example:

Figure10: Graph G
6 Algorithms and Data Structures

In graph G:
• Isolate Node : E

• Path P : A, B, D, C

• Cycle C1 : A, B, D, C, A

• Degree of a node (vertex):

• Indegree: Number of edges ending at a node.

• Outdegree: Number of edges beginning at a node.

Example:

Figure11: Graph G
In Graph G:

Indegree(A) =0 Outdegree(A) = 2
Indegree(B) =3 Outdegree(B) = 0
Indegree(C) =1 Outdegree(C) = 2
Indegree(D) =1 Outdegree(D) = 1
TechnoScan - Unit - 5 7

C function to calculate indegree and outdegree of a vertex when graph is represented


by adjacency list:
struct node
{
int vertex;
struct node *next;
};

int indegree(int v)
{
int i,j=0,k;
node *p;
for(i=0;i<n;i++)
{
p=g[i];
while(p!=NULL)
{
if(p->vertex==v)
j++;
p=p->next;
}
}
return(j);
}

int outdegree(int i)
{
int j=0;
node *p;
p=g[i];
while(p!=NULL)
{
p=p->next;
j++;
}
return(j);
}
8 Algorithms and Data Structures

Application of Graph:
Graphs can be used to model many types of relations and process dynamics in physical, biological,
social and information systems. Many practical problems can be represented by graphs.
In computer science, graphs are used to represents:
• Networks of communication,
• Data organization,
• Computational devices,
• The flow of computation, etc.

One practical example: The link structure of a website could be represented by a directed
graph. The vertices are the web pages available at the website and a directed edge from page A to
page B exists if and only if A contains a link to B. A similar approach can be taken to problems in
travel, biology, computer chip design, and many other fields.

Representations of graph:
Graph can be representing in three different ways that is:

1. Adjacency matrices. ( Sequential representation)

2. Adjacency lists.

3. Adjacency multilists.

1. Adjacency matrices: In adjacency matrices used matrix of order (n x n) where n is the


number of vertices.
Example1:

Figure12: Graph G1 (Undirected)


TechnoScan - Unit - 5 9

An adjacency matrix for the above graph is:

• There are 4 vertices so we need 4 * 4 matrixes to represents the graph.

Adjacency matrices for graph G1

• Mark 1 if there is an edge between two vertices otherwise marks 0.


• In the above graph, no edge between A to A so marks 0 and there is an edge between A
to B so marks 1.

Example2:

Figure13: Graph G2 (Directed)

An adjacency matrix for the above graph is:

Adjacency matrices for graph G2


10 Algorithms and Data Structures

2. Adjacency list: In adjacency list there is one list for each vertex in G. For an undirected graph
with n vertices and e edges, this representation requires n head nodes and 2*e list nodes
Example:

Figure13: Graph G

Adjacency list for the above graph is:

• There are 4 vertices so we need 4 head nodes to represents the graph.

• Vertex1: A

• Vertex2: B

• Vertex3: C

• Vertex4: D

Adjacency matrices for graph G


TechnoScan - Unit - 5 11

3. Adjacency multilist: In Adjacency multilists representation a new structure used consists:

Multilist representation structure

•m = Marked (visited OR not)


• vertex1 = Start vertex for edge (0, 1) = 0
• vertex2 = End vertex for edge (0, 1) = 1
• list1 = First down “List name” where vertex1 is present.
• list2 = First down “List name” where vertex2 is present.

Example:

Figure14: Graph G

Adjacency multi list for the above graph is:


12 Algorithms and Data Structures

N0, N1, N2…..N5 are number of edges created in a list form in graph G.

N0 = Edge1 = (0, 1)
N1 = Edge2 = (0, 2)
N2 = Edge3 = (0, 3)
N3 = Edge4 = (1, 2)
N4 = Edge5 = (1, 3)
N5 = Edge6 = (2, 3)

GRAPH TRAVERSAL:
Graph traversal is the technique of visiting all the nodes in a graph in a particular manner. Unlike
tree traversal, graph traversal may require that some nodes be visited more than once, since it is
not necessarily known before transitioning to a node that it has already been explored.
The order in which the vertices are visited may be important, and may depend upon the particular
algorithm. The two common traversals techniques are:

1. Depth-first-search (DFS) ( Used Stack)

2. Breadth-first-search (BFS) ( Used Queue)

1. Depth-first-search (DFS)
• We follow a path through the graph until we reach a dead end.
• We then back up until we reach a node with an edge to an unvisited node.
• We take this edge and again follow it until we reach a dead end.
• This process continues until we back up to the starting node and it has no edges to
unvisited nodes.
• Must keep track of vertices already visited to avoid cycles.
• The method can be implemented using recursion or iteration.
• Stack data structure is used to implement the DFS.
TechnoScan - Unit - 5 13

Example: Consider the following graph:

Figure15: Graph G

Suppose we start the graph traversal from vertex A.


• In DFS traversal:
• First Visit A then visit B which are adjacent to A then visit C which is adjacent to B then visit
F which are adjacent to C.
A->B->C->F
(We can also visit any adjacent node of the vertex in any sequence for example:
The sequence: A->D->G->H->I is also correct)
• After visiting F there is no more adjacent node so, back to vertex C, again there is no more
adjacent node so, back to vertex B.
• Now visit E which are adjacent to B, then visit G which are adjacent to E, then visit D which
is adjacent to G.
E->G->D
• After visiting D there is no more adjacent node so, back to vertex G.
• Now visit H which are adjacent to G, and then visit I which are adjacent to H. after visiting
I we have traversed all the nodes so we stop here.
H->I
• Finally the sequence are:
14 Algorithms and Data Structures

Algorithm:

DFS( Graph G)
{

1. Push the starting vertex onto the stack.


2. while (stack is not empty)
(a) Pop a vertex off the stack, call it v.
(b) If v is not already visited, visit it, and mark it as visited.
(c) Push all vertices adjacent to v, which is not visited,
onto the stack.
3. end
}

Time and Space Complexity:

Graph Data Structure Depth First Traversal

Worst case Time Complexity O (|E|) for explicit graphs traversed without repetition,

O (bd) for implicit graphs with branching factor b searched to depth d

Worst case space complexity O (|V|) if entire graph is traversed without repetition,

O (longest path length searched) for implicit graphs without


elimination of duplicate nodes
TechnoScan - Unit - 5 15

C function to implement DFS traversal using adjacency list:


#define TRUE 1
#define FALSE 0
struct node
{
int data;
struct node *link;
};

void dfs(int v, struct node **p)


{
struct node *q;
visited[v-1]=TRUE;
printf("%d\t", v);

q= *(p+v-1);

while(q!=NULL)
{
if(visited[q->data-1]==FALSE)
dfs(q->data, p);
else
q=q->link;
}
}
C Program to implement DFS traversal using adjacency list:
Suppose we have given the following graph and start the traversal from vertex 4:

Figure16: Graph G
16 Algorithms and Data Structures

/* C Program to traverse the graph in DFS manner */


#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
struct node
{
int data;
struct node *link;
};
struct node* create(int v); // function for create graph.
void dfs(int v, struct node **p); // function for DFS traversal.

int visited[6];

int main()
{
struct node *arr[6];
struct node *t1, *t2, *t3, *t4;
int i;
t1=create(2); // for vertex 1
arr[0]=t1;
t2=create(3);
t1->link=t2;
t2->link='\0';

t1=create(1); // for vertex 2


arr[1]=t1;
t2=create(4);
t1->link=t2;
t2->link='\0';

t1=create(1); // for vertex 3


arr[2]=t1;
t2=create(4);
t1->link=t2;
TechnoScan - Unit - 5 17

t2->link='\0';
t1=create(2); // for vertex 4
arr[3]=t1;
t2=create(3);
t1->link=t2;
t3=create(5);
t2->link=t3;
t4=create(6);
t3->link=t4;
t4->link='\0';

t1=create(4); // for vertex 5


arr[4]=t1;
t2=create(6);
t1->link=t2;
t2->link='\0';

t1=create(2); // for vertex 6


arr[5]=t1;
t2=create(5);
t1->link=t2;
t2->link='\0';

printf("\nDFS traversal of a Graph:\n");


dfs(4, arr); // Traversal start from vertex 4

printf("\n");
return 0;
}
struct node* create(int v)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=v;
return temp;
}
18 Algorithms and Data Structures

void dfs(int v, struct node **p)


{
struct node *q;
visited[v-1]=TRUE;
printf("%d\t", v);

q= *(p+v-1);

while(q!='\0')
{
if(visited[q->data-1]==FALSE)
dfs(q->data, p);
else
q=q->link;
}
}

Output:

DFS traversal of a graph:

4 2 1 3 5 6

2. Breadth-first-search(BFS):

• In BFS traversal from the starting node, we follow all paths which are adjacent to starting
node and length is one.

• Then we follow paths of length two that go to unvisited nodes.

• We continue increasing the length of the paths until there are no unvisited nodes along
any of the paths.
• Must keep track of vertices already visited to avoid cycles.
• Queue data structure is used to implement the BFS.
TechnoScan - Unit - 5 19

Example: Consider the following graph:

Figure17: Graph G

• Suppose we start the graph traversal from vertex A.


• In BFS traversal:
• First Visit A then visit B which are adjacent to A then visit D which is adjacent to A then visit
E which are adjacent to A.
A->B->D->E
(We can also visit any adjacent node of the vertex in any sequence for example:
The sequence: A->B->E->D is also correct)
• After visiting E we have finished the entire node which are adjacent to A. so now expand
the path from B.
• Now visit C which is adjacent to B.
C
• Now visit G which is adjacent to E.
G
• Now visit F which is adjacent to C.
F
• Now visit H which is adjacent to G and then visit I which is adjacent to H. after visiting H
we have traversed all the nodes so we stop here.
H->I
20 Algorithms and Data Structures

• Finally the sequence are:

Algorithm:

BFS( Graph G)
{

Insert the starting vertex onto the queue.


while(queue is not empty)
{
Delete a vertex off the queue, call it v.
If v is not already visited, visit it, and mark it as visited.
Insert all vertices adjacent to v, which is not visited, onto the
queue.
}

}
Time and Space Complexity:
Time complexity
The time complexity can be expressed as O(|V|+|E|) since every vertex and every edge
will be explored in the worst case.
Space complexity
The space complexity can be expressed as O(|V|) where |V| is the cardinality of the set of
vertices. If the graph is represented by an Adjacency list it occupies Q(|V|+|E|) space in
memory, while an Adjacency matrix representation occupies Q(|V|2).

C function to implement BFS traversal using adjacency list:


#define TRUE 1
#define FALSE 0
struct node
{
int data;
struct node *link;
};
TechnoScan - Unit - 5 21

void bfs(int v, struct node **p)


{
struct node *q;
visited[v-1]=TRUE;
printf("%d\t", v);

insertq(v);
while(f ! = -1)
{
v = deleteq();
q= *(p+v-1);

while(q!=NULL)
{
if(visited[q->data-1]==FALSE)
{
insertq(q->data);
visited[q->data-1]=TRUE;
printf("%d\t", q->data);
}
q=q->link;
}
}
}

C Program to implement BFS traversal using adjacency list:


Suppose we have given the following graph and start the traversal from vertex 4:

Figure18: Graph G
22 Algorithms and Data Structures

/* C Program to traverse the graph in BFS manner */


#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
struct node
{
int data;
struct node *link;
};
struct node* create(int v); //fn for create graph
void bfs(int v, struct node **p); // fn for DFS traversal
void insertq(int n);
int deleteq();

int visited[6];
int f=-1,r=-1;
int q[6];

int main()
{
struct node *arr[6];
struct node *t1, *t2, *t3, *t4;
int i;
t1=create(2); // for vertex 1
arr[0]=t1;
t2=create(3);
t1->link=t2;
t2->link='\0';

t1=create(1); // for vertex 2


arr[1]=t1;
t2=create(4);
t1->link=t2;
t2->link='\0';
t1=create(1); // for vertex 3
TechnoScan - Unit - 5 23

arr[2]=t1;
t2=create(4);
t1->link=t2;
t2->link='\0';

t1=create(2); // for vertex 4


arr[3]=t1;
t2=create(3);
t1->link=t2;
t3=create(5);
t2->link=t3;
t4=create(6);
t3->link=t4;
t4->link='\0';

t1=create(4); // for vertex 5


arr[4]=t1;
t2=create(6);
t1->link=t2;
t2->link='\0';

t1=create(2); // for vertex 6


arr[5]=t1;
t2=create(5);
t1->link=t2;
t2->link='\0';

printf("\nBFS traversal of a Graph:\n");


bfs(4, arr); // Traversal start from vertex 4

printf("\n");
return 0;
}
24 Algorithms and Data Structures

struct node* create(int v)


{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=v;
return temp;
}

void insertq(int n)
{

if(r==5)
{
printf("Queue is full");
return;
}
r++;
q[r] = n;
if(f==-1)
f=0;
}

int deleteq()
{
int d;
if(f==-1)
{
printf("Queue is empty");
return;

}
d=q[f];
if(f==r)
{
f = -1;
r = -1;
}
TechnoScan - Unit - 5 25

else
f++;
return d;
}

void bfs(int v, struct node **p)


{
struct node *q;
visited[v-1]=TRUE;
printf("%d\t", v);

insertq(v);
while(f!=-1)
{
v = deleteq();
q= *(p+v-1);

while(q!=NULL)
{
if(visited[q->data-1]==FALSE)
{
insertq(q->data);
visited[q->data-1]=TRUE;
printf("%d\t", q->data);
}
q=q->link;
}
}
}

Output:

DFS traversal of a graph:

4 2 3 5 6 1
26 Algorithms and Data Structures

Comparison between depth first search and breadth first search:

Depth First Search (DFS) Breadth First Search (BFS)

1. Depth First Search (also known as DFS) is a 1. Breadth First Search (also known as BFS) is
search method that goes deeper into a child a search method used to expand all the nodes
node of a search until a goal is reached. of a particular graph.

2. DFS uses stack (LIFO) for implementation. 2. BFS uses queue (FIFO) for implementation.

3. Required less memory as compare to BFS 3. Required more memory as compare to DFS

4. DFS is faster than BFS 4. BFS is slower than DFS

5. DFS are used to perform recursive procedures. 5. Perform non-recursive procedure.

SPANNING TREES:

First let's define a tree, a spanning tree, and a minimum cost spanning tree:

Tree: is a connected, undirected graph without cycles. (A cycle is a path that starts and
ends at the same vertex.)

Spanning tree: A spanning tree of the graph is a connected, undirected subgraph that
includes each vertex of the graph in which there are no cycles.

• Connected means every node is reachable from every other node.

• Undirected means edges do not have an associated direction.

Example: consider the following graph:-

Figure19: Graph G
TechnoScan - Unit - 5 27

Different spanning tree can be:

Figure20: possible spanning of graph G

Note: If we traverse the graph in DFS or BFS manner, we will find many DFS and BFS
spanning tree. Try it!

Minimum cost spanning tree (MST):

This is only defined for weighted graphs. This is the spanning tree of a given graph whose sum of
edge weights is minimum, compared to all other spanning trees.

• Suppose you have a connected undirected graph with a weight (or cost) associated with
each edge
• The cost of a spanning tree would be the sum of the costs of its edges
• A minimum-cost spanning tree is a spanning tree that has the lowest cost
28 Algorithms and Data Structures

Example: Consider the following graph:

Figure21: Connected and weighted graph


Look three different spanning tree of the above graph with cost:

A spanning tree with cost = 23


Spanning tree: 1
TechnoScan - Unit - 5 29

Another spanning tree with cost = 21


Spanning tree: 2

MST cost = 15
Spanning tree: 3
So, spanning tree: 3 is the minimum cost spanning tree of the above given graph.
30 Algorithms and Data Structures

There are two basic algorithms for finding minimum-cost spanning trees and both follows the
greedy approach:
• Kruskal’s algorithm: Start with no nodes or edges in the spanning tree, and repeatedly
add the cheapest edge that does not create a cycle.
• Prim’s algorithm: Start with any one node in the spanning tree, and repeatedly add the
cheapest edge, and the node it leads to, for which the node is not already in the spanning tree.
Greedy algorithm:
• A “greedy algorithm” works well for optimization problems
• An optimization problem is one in which you want to find, not just a solution, but the best
solution
• A greedy algorithm works in phases. At each phase:
• You take the best you can get right now, without regard for future consequences
• You hope that by choosing a local optimum at each step, you will end up at a global
optimum.

Kruskal’s algorithm:
Kruskal’s algorithm is a greedy algorithm that finds a minimum spanning tree for a connected
weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes
every vertex, where the total weight of all the edges in the tree is minimized.
Procedure:
• List all the edges of the graph.
• Sort all edges in increasing order according to its weight.
• Select the cheapest edge in the graph. If there is more than one, pick one at random and
mark.
• Find the next cheapest edge in the graph. If there is more than one, pick one at random
and if it makes no cycle then add to the spanning tree and mark.
• Find the next cheapest unmarked edge in the graph that does not create a cycle and add
to the spanning tree and mark. If there is more than one, pick one at random.
• Repeat the previous step until the path spans every vertex of the graph that means we
have (n-1) edges in the spanning tree. It will be the minimal spanning tree (MST).
Basically, you build the MST of the graph by continually adding in the smallest weighted edge into
the MST that doesn't form a cycle. When you are done, you'll have an MST. You HAVE to make
sure you never add an edge the forms a cycle and that you always add the minimum of ALL the
edges left that don't.
The reason this works is that each added edge is connecting between two sets of vertices, and since
we select the edges in order by weight, we are always selecting the minimum edge weight that
connects the two sets of vertices.
TechnoScan - Unit - 5 31

Example:
Let’s consider the following graph:

Figure: 22 Connected, weighted graph G.

Solution by using krushkal’s algorithm:


Sr. No. Edge Cost Add to Spanning Tree
1. (a,c) 3 Yes
2. (b,c) 3 Yes
3. (a,b) 4 No (Make Cycle)
4. (b,d) 5 Yes
5. (c,d) 8 No (Make Cycle)
6. (c,f) 9 Yes
7. (e,g) 10 Yes
8. (e,f) 11 Yes
9. (d,g) 12 No
10. (f,g) 14 No
11. (b,e) 18 No
32 Algorithms and Data Structures

Minimum Cost Spanning Tree is:

Cost is 3+3+5+9+10+11 = 41.

Algorithm:

Input: A connected undirected graph G (V, E) with edge weight we.


Output: A minimum spanning tree T.

Krushkal’s (G, W)
{
1. Let T = 
2. For i=1 to n-1, (where there are n vertices in a graph)
T = T e, where e is the edge with the minimum edge
weight not already in T, and that does NOT
form a cycle when added to T.
3. Return T
}
TechnoScan - Unit - 5 33

Prim’s algorithm: Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for
a connected weighted undirected graph. This means it finds a subset of the edges that forms a tree
that includes every vertex, where the total weight of all the edges in the tree is minimized.
Procedure:

1. Initialize a tree with a single vertex, chosen arbitrarily from the graph.
2. List all the edges which are adjacent to chosen vertices.
3. Select edge from the list which has minimum cost, remove from the list and grow the tree
by one edge if it not make cycles. If there is more than one, pick one at random
4. Repeat step 2 (until all vertices are in the tree).

Once again, this works directly because of the theorem discussed before. In particular, the
set you are growing is the partition of vertices and each edge you add is the smallest edge
connecting that set to its complement.
For cycle detection, note that at each iteration, you must add exactly one vertex into the subgraph
represented by the edges.

Example: Let’s consider the following graph:

Figure: 23 Connected, weighted graph G.

Solution by using Prim’s algorithm:

Step 1: Start from any vertex Say - A

List = {(A,B) - 2,
(A,D) - 4,
(A,C) - 4,
}
34 Algorithms and Data Structures

Step 2: Select edge (A,B) since it has minimum cost


List = {(A,D) - 4,
(A,C) - 4,
(B,C) - 3
}

Step 3: Select edge (B,C)


List = {(A,D) - 4,
(A,C) - 4,
(C,D) - 2
}
TechnoScan - Unit - 5 35

Step 4: Select edge (C,D)


List = {(A,D) - 4,
(A,C) - 4,
(D,E) - 5,
(D,F) - 6,
}

Step 5: edge (A,D) make cycle


edge (A,C) make cycle
Select edge (D,E)
List - {(D,F) - 6,
(E,G) - 7,
}
36 Algorithms and Data Structures

Step 6: Select edge (D,F)


List - {(E,G) - 7,
(F,G) - 8,
}

Step 7: Select edge (E,G)


List - {(F,G) - 8}

We stop here -
Cost is 2+2+3+5+6+7 = 25
TechnoScan - Unit - 5 37

Algorithm:
Input: A connected undirected graph G (V, E) with edge weight we.
Output: A minimum spanning tree T.
Prim’s (G, W)
{
1. T = a spanning tree containing a single node s;
2. E = set of edges adjacent to s;
3. while T does not contain all the nodes
{
remove an edge (v, w) of lowest cost from E
if w is already in T then discard edge (v, w)
else
{
add edge (v, w) and node w to T
add to E the edges adjacent to w
}
}
4. end
}

Shortest Path Algorithm:

Weighted graph representing a network of airports, the weights could represent: distance, cost or
time. Such a graph could be used to answer any of the following:
• What is the fastest way to get from A to B?
• Which route from A to B is the least expensive?
• What is the shortest possible distance from A to B?
Each of these questions is an instance of the same problem: The shortest path problem!
Single-Source Shortest Path Problem - The problem of finding shortest paths from a source
vertex v to all other vertices in the graph. Suppose you have five towns surrounding you. You
determine the amount of time it takes between certain cities on connecting one-way roads. You
would like to determine the shortest path from your town to each of the other cities. You do not
need to visit every city, but you will have a path specified for every destination.
38 Algorithms and Data Structures

Dijkstra's algorithm - is a solution to the single-source shortest path problem in graph theory.
Works on both directed and undirected graphs. However, all edges must have nonnegative weights.
Approach is: Greedy
Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step.
1. Assign to every node a tentative distance value: set it to zero for our initial node and to
infinity for all other nodes.
2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes
called the unvisited set consisting of all the nodes.
3. For the current node, consider all of its unvisited neighbors and calculate their tentative
distances.
4. When we are done considering all of the neighbors of the current node, mark the current
node as visited and remove it from the unvisited set. A visited node will never be checked
again.
5. If the destination node has been marked visited then stop. The algorithm has finished.
6. Otherwise, Select the unvisited node that is marked with the smallest tentative distance,
and set it as the new "current node" then go back to step 3.
Example: consider the following given graph:

Suppose we start from vertex ‘f’ and end from vertex ‘g’
Solution:
Intially: T={a,b,c,d,e,f,g}

L(x) =
TechnoScan - Unit - 5 39

Now the starting vertex is ‘f’ so, mark 0 (zero) of the legth ‘f’ and others to infinity () and remove
vertex ‘f’ from set T.

L(x) =

t = {a,b,c,d,e,g}
Step 1: Find all the adjacent node of ‘f’ which is in set T. In this case edge is,
f - a with cost 2
f - d with cost 3
Now update the length (cost) if it is minimum.

So, L(x) =

Step 2: Now, select the node with minimum length from the set T.
In this case we select ‘a’, remove vertex from ‘a’ from set T. Find all the adjacent
node of ‘a’ which is in set T. in this case edge is:
a - c (from f cost is 2+1 = 3)
a - b (from f cost is 2+4 = 6)

Now update the length (cost) if it is minimum:

So, L(x) =

and T = {b,c,d,e,g)

Step 3: Now select the node with minimum length from set T.
In this case we select ‘c’. Remove vertex ‘c’ from the set T. Find all the adjacent
node of ‘c’ which is in set T. In this case edge is:
c - b (from f cost is 3+1 = 4)
c - g (from f cost is 3+3 = 6)
Now update the length (cost) if it is minimum:

So, L(x) =

T = {b,d,e,g}
40 Algorithms and Data Structures

Step 4: Now select the node with minimum length from set T.
In this case we select ‘d’. Remove vertex ‘d’ from the set T. Find all the adjacent
node of ‘d’ which is in set T. In this case edge is:
d - b (from f cost is 3+5 = 8)
d - e (from f cost is 3+6 = 9)
Now update the length (cost) if it is minimum:

So, L(x) =

T = {b,e,g}

Step 5: Now select the node with minimum length from set T.
In this case we select ‘b’. Remove vertex ‘b’ from the set T. Find all the adjacent
node of ‘b’ which is in set T. In this case edge is:
b - e (from f cost is 4+2 = 6)
Now update the length (cost) if it is minimum:

So, L(x) =

T = {e,g}

Step 6: Now select the node with minimum length from set T.
In this case we can select ‘g’. Seince e and g are both equal remove vertex ‘g’
from the set T. So, we reached the destination, and stop here finally we get

L(x) =

This is the minimum length of all vertex when we start from vertex ‘f’.
TechnoScan - Unit - 5 41

Dijkstra's Algorithm
• Given a connected, positive weighted graph.
• Find out the length of a shortest path from vertex f to g.
Input: A connected, positive weighted graph W, source vertices f, destination vertices g and
length L.

Dijkshtra (W, f, g, L)
{
1. L(f) = 0.
2. For all vertices x = f.
L(x) = 00.
T = Set of all vertices.
3. While (geT)
{
Choose veT with minimum L(v).
T = T-{V}.
For each X e T adjacent to v.
L(x) = min(L(x), L(v)+W(v,x))
}
4. end
}
42 Algorithms and Data Structures

University Asked Questions:

1. Define graph data structure and explain various graph terminologies.

[ S-12 (4) W-10 (4) W-08 (6)]

2. What are the different ways to representing graph?

[S-13 (3), W-10 (4), S-09 (7), S-11 (6)]

3. Explain the depth first search (DFS) with suitable example. Write the algorithm for Depth
first search traversal and discuss the time and space complexity.

[S-13 (6), S-11 (8), W-12 (4), S-12 (3) W-07 (4), W-06 (7)]

4. Explain the Breadth first search (BFS) with suitable example. Write the algorithm for
Breadth first search traversal and find the time and space complexity

[W-12 (4), W-10 (5), W-08 (7), S-10 (7) S-12 (3), W-07 (4)]

5. Explain the different between DFS and BFS graph traversal technique. Which one is best?
Justify your answer.

[S-09 (6) S-08 (5) S-06 (4)]

6. Explain the kruskal’s algorithm to find the minimum cost spanning tree with suitable
example.

[W-11 (6) W-07 (3) W-06 (7)]

7. Explain the prim’s algorithm with suitable example.

[W-07 (3)]

8. Define shortest path and explain Dijkshtra’s algorithms in detail with suitable example.

[S-11 (8) S-10 (7) S-07 (9) S-06 (3), W-12 (7), W-06 (6)]



You might also like