Created
January 24, 2016 13:25
-
-
Save rohitvvv/e201760db65d6b9cb481 to your computer and use it in GitHub Desktop.
BFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ouputs 2 3 0 1