Skip to content

Instantly share code, notes, and snippets.

@rohitvvv
Created January 24, 2016 13:25
Show Gist options
  • Save rohitvvv/e201760db65d6b9cb481 to your computer and use it in GitHub Desktop.
Save rohitvvv/e201760db65d6b9cb481 to your computer and use it in GitHub Desktop.
BFS
package com.company;
import java.util.Iterator;
import java.util.LinkedList;
public class Main {
private int V; //number of vertices.
private LinkedList<Integer> adj[];
//Constructor that inialises and sets memory for the adj list
Main(int v){
V=v;
adj= new LinkedList[v];
for(int i=0;i<v;i++)
adj[i] = new LinkedList<>();
}
//method to build the adj list.
void addEdge(int v,int w){
adj[v].add(w);
}
//pass the root
void BFS(int root){
boolean []visited = new boolean[V];
LinkedList<Integer> queue = new LinkedList<>();
visited[root]=true;
queue.add(root);
while(queue.size()!=0) {
root = queue.poll();
System.out.println(" "+root);
Iterator<Integer> i = adj[root].listIterator();
while(i.hasNext()){
int n = i.next();
if(!visited[n]){
visited[n]=true;
queue.add(n);
}
}
}
}
public static void main(String[] args) {
Main g = new Main(4);
g.addEdge(2,3);
g.addEdge(3,3);
g.addEdge(2,0);
g.addEdge(0,2);
g.addEdge(1, 2);
g.addEdge(0, 1);
g.BFS(2);
}
}
@rohitvvv
Copy link
Author

Ouputs 2 3 0 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment