diff --git a/01. Graphs/02. BFS/BFS Algo b/01. Graphs/02. BFS/BFS Algo new file mode 100644 index 0000000..d09650c --- /dev/null +++ b/01. Graphs/02. BFS/BFS Algo @@ -0,0 +1,54 @@ +import java.util.*; +class Solution { + // Function to return Breadth First Traversal of given graph. + public ArrayList bfsOfGraph(int V, + ArrayList> adj) { + + ArrayList < Integer > bfs = new ArrayList < > (); + boolean vis[] = new boolean[V]; + Queue < Integer > q = new LinkedList < > (); + + q.add(0); + vis[0] = true; + + while (!q.isEmpty()) { + Integer node = q.poll(); + bfs.add(node); + + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + for (Integer it: adj.get(node)) { + if (vis[it] == false) { + vis[it] = true; + q.add(it); + } + } + } + + return bfs; + } + + public static void main(String args[]) { + + ArrayList < ArrayList < Integer >> adj = new ArrayList < > (); + for (int i = 0; i < 5; i++) { + adj.add(new ArrayList < > ()); + } + adj.get(0).add(1); + adj.get(1).add(0); + adj.get(0).add(4); + adj.get(4).add(0); + adj.get(1).add(2); + adj.get(2).add(1); + adj.get(1).add(3); + adj.get(3).add(1); + + Solution sl = new Solution(); + ArrayList < Integer > ans = sl.bfsOfGraph(5, adj); + int n = ans.size(); + for(int i = 0;i