From 83ddeb9a1dc7e72919dd160b364c84e72ed59755 Mon Sep 17 00:00:00 2001 From: $iD <32844499+siddhartthecoder@users.noreply.github.com> Date: Mon, 1 Oct 2018 02:09:59 +0530 Subject: [PATCH] Create Graph.java --- Java/algorithms/Graph.java | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Java/algorithms/Graph.java diff --git a/Java/algorithms/Graph.java b/Java/algorithms/Graph.java new file mode 100644 index 0000000..5eaff67 --- /dev/null +++ b/Java/algorithms/Graph.java @@ -0,0 +1,63 @@ + +import java.io.*; +import java.util.*; +class Graph +{ + private int V; + private LinkedList adj[]; + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i queue = new LinkedList(); + + visited[s]=true; + queue.add(s); + + while (queue.size() != 0) + { + s = queue.poll(); + System.out.print(s+" "); + + Iterator 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); + } +}