diff --git a/Traversals/GraphBFSAdjList.java b/Traversals/GraphBFSAdjList.java index 6903813..79f1bb0 100644 --- a/Traversals/GraphBFSAdjList.java +++ b/Traversals/GraphBFSAdjList.java @@ -1,3 +1,16 @@ +# Breadth First Search Using Adjacent List + +## BFS Algorithm + The general process of exploring a graph using breadth-first search using adjacency list includes the following steps:- + + -Take the input of adjacency list for the graph. + -Initialize a queue. + -Enqueue the root node (in other words, put the root node into the beginning of the queue. + -Dequeue the head (or first element) of the queue, then enqueue all of its neighboring nodes, starting from left to right. If a node has no neighboring nodes which need to be explored, simply dequeue the head and continue the process. (Note: If a neighbor which is already explored or in the queue appears, don’t enqueue it – simply skip it.) + -Keep repeating this process till the queue is empty. + + + import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; @@ -59,4 +72,11 @@ public static void main(String[] args) { System.out.println("BFS:"); g.bfs(2); } -} \ No newline at end of file +} + +## Time and Space Complexities + +The running time complexity of the BFS in Java is O(V+E) where V is the number of nodes in the graph, and E is the number of edges. + +Since the algorithm requires a queue for storing the nodes that need to be traversed at any point in time, the space complexity is O(V). +