0% found this document useful (0 votes)
13 views2 pages

Graph Traversals (BFS, DFS)

Uploaded by

rahulgattadi458
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Graph Traversals (BFS, DFS)

Uploaded by

rahulgattadi458
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

19 .

BFS (Breadth First Search)

import java.util.*;
public class Graph {
private int V;
private LinkedList<Integer> adj[];

// Create a graph
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

// Add edges to the graph


void addEdge(int v, int w) {
adj[v].add(w);
}
// BFS algorithm
void BFS(int s) {

boolean visited[] = new boolean[V];


LinkedList<Integer> queue = new LinkedList();
visited[s] = true;
queue.add(s);
while (queue.size() != 0) {
s = queue.poll();
System.out.print(s + " ");

Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String args[]) {
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Breadth First Traversal " + "(starting from vertex 2)");


g.BFS(2);
}
}
20. DFS (Depth First Search)

import java.util.*;
class Graph {
private LinkedList<Integer> adjLists[];
private boolean visited[];

// Graph creation
Graph(int vertices) {
adjLists = new LinkedList[vertices];
visited = new boolean[vertices];

for (int i = 0; i < vertices; i++)


adjLists[i] = new LinkedList<Integer>();
}

// Add edges
void addEdge(int src, int dest) {
adjLists[src].add(dest);
}

// DFS algorithm
void DFS(int vertex) {
visited[vertex] = true;
System.out.print(vertex + " ");

Iterator<Integer> ite = adjLists[vertex].listIterator();


while (ite.hasNext()) {
int adj = ite.next();
if (!visited[adj])
DFS(adj);
}
}

public static void main(String args[]) {


Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);

System.out.println("Following is Depth First Traversal");

g.DFS(2);
}
}

You might also like