| 3 | import java.util.*; |
| 4 | |
| 5 | public class Graph { |
| 6 | private int V; |
| 7 | private LinkedList<Integer> adj[]; |
| 8 | |
| 9 | // Create a graph |
| 10 | Graph(int v) { |
| 11 | V = v; |
| 12 | adj = new LinkedList[v]; |
| 13 | for (int i = 0; i < v; ++i) |
| 14 | adj[i] = new LinkedList(); |
| 15 | } |
| 16 | |
| 17 | // Add edges to the graph |
| 18 | void addEdge(int v, int w) { |
| 19 | adj[v].add(w); |
| 20 | } |
| 21 | |
| 22 | // BFS algorithm |
| 23 | void BFS(int s) { |
| 24 | |
| 25 | boolean visited[] = new boolean[V]; |
| 26 | |
| 27 | LinkedList<Integer> queue = new LinkedList(); |
| 28 | |
| 29 | visited[s] = true; |
| 30 | queue.add(s); |
| 31 | |
| 32 | while (queue.size() != 0) { |
| 33 | s = queue.poll(); |
| 34 | System.out.print(s + " "); |
| 35 | |
| 36 | Iterator<Integer> i = adj[s].listIterator(); |
| 37 | while (i.hasNext()) { |
| 38 | int n = i.next(); |
| 39 | if (!visited[n]) { |
| 40 | visited[n] = true; |
| 41 | queue.add(n); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | public static void main(String args[]) { |
| 48 | Graph g = new Graph(4); |
| 49 | |
| 50 | g.addEdge(0, 1); |
| 51 | g.addEdge(0, 2); |
| 52 | g.addEdge(1, 2); |
| 53 | g.addEdge(2, 0); |
| 54 | g.addEdge(2, 3); |
| 55 | g.addEdge(3, 3); |
| 56 | |
| 57 | System.out.println("Following is Breadth First Traversal " + "(starting from vertex 2)"); |
| 58 | |
| 59 | g.BFS(2); |
| 60 | } |
| 61 | } |
nothing calls this directly
no outgoing calls
no test coverage detected