You are on page 1of 7

NAME: Dhanush

REG NO.: 21BCE8317

DATA STRUCTURE
ASSIGNMENT-10
1. Write a program to implement DFS algorithm
and print the DFS sequence for below graph
start with node D
CODE:
import java.io.*;
import java.util.*;
class Graph {
private int V;
private LinkedList<Integer> adj[];
@SuppressWarnings("unchecked")
Graph(int v){
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w){
adj[v].add(w);
}
void DFS_traversal(int v, boolean visited[]){
visited[v] = true;
System.out.print(v + " ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFS_traversal(n, visited);
}
}
void DFS(int v){
boolean visited[] = new boolean[V];
DFS_traversal(v, visited);
}
}
class Main{
public static void main(String args[]){
Graph graph = new Graph(8);
graph.addEdge(0, 1);
graph.addEdge(7,1);
graph.addEdge(6,7);
graph.addEdge(6,3);
graph.addEdge(4,6);
graph.addEdge(3,4);
graph.addEdge(3,2);
graph.addEdge(3,5);
graph.addEdge(5,2);
System.out.println("Depth First Traversal from vertex
D ");
graph.DFS(3);
System.out.println("Dhanush 21BCE8317");
}
}

OUTPUT:
2. Write a program to implement BFS algorithm
and print the BFS sequence start with node A
CODE:
import java.io.*;
import java.util.*;
class Graph{
private int V;
private LinkedList<Integer> adj[];
private Queue<Integer> queue;
Graph(int v){
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; i++){
adj[i] = new LinkedList<>();
}
queue = new LinkedList<Integer>();
}
void addEdge(int v,int w){
adj[v].add(w);
}
void BFS(int n){
boolean nodes[] = new boolean[V];
int a = 0;
nodes[n]=true;
queue.add(n);
while (queue.size() != 0){
n = queue.poll();
System.out.print(n+" ");
for (int i = 0; i < adj[n].size(); i++) {
a = adj[n].get(i);
if (!nodes[a]) {
nodes[a] = true;
queue.add(a);
}
}
}
}
}
class Main{
public static void main(String args[]){
Graph graph = new Graph(8);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(1, 5);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
graph.addEdge(4, 6);
graph.addEdge(5, 6);
System.out.println("The Breadth First Traversal of
the graph from A :");
graph.BFS(0);
System.out.println("Dhanush 21BCE8317");
}
}

OUTPUT:

You might also like