0% found this document useful (0 votes)
6 views

DS JAVA_11th Lab Program

Uploaded by

janakirampilli70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DS JAVA_11th Lab Program

Uploaded by

janakirampilli70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Graphs

31. Write Java programs for the implementation of bfs and dfs for a given graph.

Note: Refer chapter 16: Graphs for more detailed discussion.

Graph Traversals
A primary problem concerning the graphs is the reachability. A number of graph problems involve
traversal of a graph. Traversal of a graph means visiting each of its nodes exactly once. This is
accomplished by visiting the nodes in a systematic manner. Two commonly used techniques of graph
traversal are depth-first search (DFS) and breadth-first search (BFS). These algorithms work for both
directed and undirected graphs.

Depth-First Search
Depth-first search is a generalization of the preorder traversal of a tree. DFS can serve as a structure
around which many other efficient graph algorithms can be built.
As an example of dfs, suppose in the graph of the following figure, we start at node A. A
complete program listing is given in Program 31(a).

A A B D E X A B C D E

B A C D X A 0 1 0 1 1
B 1 0 1 1 0
B D C B D E X
E C 0 1 0 1 1
D A B C X D 1 1 1 0 0

C E A C X E 1 0 1 0 0

Undirected Graph Adjacency list Adjacency matrix

Program 31(a): Depth-First Search


class Node
{ int label; // vertex label
Node next; // next node in list
Node( int b ) // constructor
{ label = b; }
}
class Graph
{ int size;
Node adjList[];
int mark[];
Graph(int n) // constructor
{ size = n;
82 Lab Manual Data Structures through Java

adjList = new Node[size];


mark = new int[size]; // elements of mark are initialized to 0
}
public void createAdjList(int a[][]) // create adjacent lists
{
Node p; int i, k;

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


{ p = adjList[i] = new Node(i); //create first node of ith adj. list
for( k = 0; k < size; k++ )
{ if( a[i][k] == 1 )
{ p.next = new Node(k); // create next node of ith adj. list
p = p.next;
}
}
}
}
public void dfs(int head) // recursive depth-first search
{ Node w; int v;
mark[head] = 1;
System.out.print( head + " ");
w = adjList[head];
while( w != null)
{ v = w.label;
if( mark[v] == 0 ) dfs(v);
w = w.next;
}
}
}
///////////////////////// DfsDemo.java ////////////////////////
class DfsDemo
{ public static void main(String[] args)
{ Graph g = new Graph(5); // graph is created with 5 nodes

int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},


{1,1,1,0,0}, {1,0,1,0,0}};
g.createAdjList(a);
g.dfs(0); // starting node to dfs is 0 (i.e., A)
}
}

Output of this program is: 0 1 2 3 4


Here, 0 is for A, 1 is for B, 2 is for C, 3 is for D, and 4 is for E

Breadth-First Search
Another systematic way of visiting the nodes is called breadth-first search (bfs). The approach is called
“breadth-first” because from each node v that we visit we search as broadly as possible by next visiting all
nodes adjacent to v.
The breadthFirstSearch algorithm inserts a node into a queue, which we assume is initially empty.
Every entry in the array mark is assumed to be initialized to the value unvisited. If the graph is not
connected, bfs must be called on a node of each connected component. Note that in bfs we must mark a
node visited before inserting it into the queue, to avoid placing it on the queue more than once. The
algorithm terminates when the queue becomes empty.
8. Graphs 83

We assume the graph is represented by an adjacency list and is globally available. The algorithm
depends on the availability of an implementation of a queue of integers (here, a simple queue is assumed;
not circular queue). Three methods relating to queue: qinsert(), qdelete(), and isEmpty() are to be properly
defined before the method for bfs is defined.

Program 31(b): Breadth-First Search


class Node
{ int label; // vertex label
Node next; // next node in list
Node( int b ) // constructor
{ label = b; }
}

class Graph
{ int size;
Node adjList[];
int mark[];

Graph(int n) // constructor
{ size = n;
adjList = new Node[size];
mark = new int[size];
}
public void createAdjList(int a[][]) // create adjacent lists
{ Node p; int i, k;
for( i = 0; i < size; i++ )
{ p = adjList[i] = new Node(i);

for( k = 0; k < size; k++ )


{ if( a[i][k] == 1 )
{ p.next = new Node(k);
p = p.next;
}
} // end of inner for-loop
} // end of outer for-loop
} // end of createAdjList()
public void bfs(int head)
{ int v; Node adj;
Queue q = new Queue(size);
v = head;
mark[v] = 1;
System.out.print(v + " ");
q.qinsert(v);
while( !q.IsEmpty() ) // while(queue not empty)
{
v = q.qdelete();
adj = adjList[v];

while( adj != null )


{ v = adj.label;

if( mark[v] == 0 )
{ q.qinsert(v);
mark[v] = 1;
System.out.print(v + " ");
}
84 Lab Manual Data Structures through Java

adj = adj.next;
}
}
}
} // end of Graph class

class Queue
{ private int maxSize; // max queue size
private int[] que; // que is an array of integers
private int front;
private int rear;
private int count; // count of items in queue
public Queue(int s) // constructor
{ maxSize = s;
que = new int[maxSize];
front = rear = -1;
}
public void qinsert(int item)
{ if( rear == maxSize-1 )
System.out.println("Queue is Full");
else { rear = rear + 1;
que[rear] = item;
if( front == -1 ) front = 0;
}
}
public int qdelete()
{ int item;
if( IsEmpty() )
{ System.out.println("\n Queue is Empty");
return(-1);
}
item = que[front];
if( front == rear ) front = rear = -1;
else front = front+1;
return(item);
}
public boolean IsEmpty()
{ return( front == -1 ); }

} // end of Queue class


//////////////////////////////////////////////////////////
class BfsDemo
{ public static void main(String[] args)
{ Graph g = new Graph(5);

int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},


{1,1,1,0,0}, {1,0,1,0,0}};
g.createAdjList(a);
g.bfs(0);
}
}

Output of this program is: 0 1 3 4 2

You might also like