From 369a40e7efda0113c89184346173ae2d9e9e23d6 Mon Sep 17 00:00:00 2001 From: Thanistas Date: Tue, 25 Oct 2022 20:41:26 +0530 Subject: [PATCH] Create BFS algorithm --- BFS algorithm.java | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 BFS algorithm.java diff --git a/BFS algorithm.java b/BFS algorithm.java new file mode 100644 index 00000000..c0a10402 --- /dev/null +++ b/BFS algorithm.java @@ -0,0 +1,74 @@ + +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(" Breadth First Traversal "+ + "(starting from vertex 2)"); + + g.BFS(2); + } +}