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 graph; | |
import java.util.Iterator; | |
import java.util.LinkedList; | |
/** | |
* Created by panded4 on 6/11/2017. | |
*/ | |
public class BFS { | |
int v; | |
LinkedList<Integer> adj[]; | |
public BFS(int v) { | |
this.v = v; | |
adj = new LinkedList[v]; | |
for (int i = 0; i < v; i++) { | |
adj[i] = new LinkedList<>(); | |
} | |
} | |
public static void main(String[] args) { | |
BFS g = new BFS(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.bfsUtil(2); | |
} | |
private void bfsUtil(int s) { | |
boolean visited[] = new boolean[v]; | |
LinkedList<Integer> queue = new LinkedList<Integer>(); | |
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); | |
} | |
} | |
} | |
} | |
private void addEdge(int i, int w) { | |
adj[i].add(w); | |
} | |
} |
No comments:
Post a Comment