Open In App

BFS using JavaScript

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

BFS stands for Breadth First Search is a traversal technique used to traverse a graph. In BFS, we explore the graph level by level, visiting all the neighbors of a node before moving on to its neighbors' neighbors. This means that we prioritize exploring the breadth of the graph rather than its depth.

Example:

Input: n=6  
Graph= [ [2], [3,4], [2,5], [2,5] , [4,6] [4,5] ]

Output: 1 , 2 , 3 , 4 , 5 , 6

Breadth First Search in JavaScript

  • First, take input in the form of edges. Now declare an adjacency list to store the graph.
  • For each given edge put the neighbor of the first element in the list of neighbors of the second element and vice versa. Declare a visited array, and a queue, and add the first node to it.
  • Now declare a while loop which will run until the queue does not become empty.
  • In each iteration remove an element from the queue and mark the visit of that element as true.
  • Now, for all the elements in that element's adjacency list, check if that element is already visited and if not, add them to the queue. It will be repeated until the queue becomes empty.

Example: The example shows the implementation of BFS using JavaScript.

JavaScript
class Graph {
    constructor(v) {
        this.V = v;
        this.adj = new Array(v).fill(null)
                               .map(() => []);
    }

    // Function to add an edge into the graph
    addEdge(v, w) {
        this.adj[v].push(w);
    }

    // Prints BFS traversal from all unvisited vertices
    BFS() {
        let visited = new Array(this.V).fill(false);

        for (let i = 0; i < this.V; ++i) {
            if (!visited[i]) {
                let queue = [];
                visited[i] = true;
                queue.push(i);

                while (queue.length !== 0) {
                    let s = queue.shift();
                    process.stdout.write(s + " ");
                    for (let n of this.adj[s]) {
                        if (!visited[n]) {
                            visited[n] = true;
                            queue.push(n);
                        }
                    }
                }
            }
        }
    }
}

let 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);

console.log("Following is Breadth First Traversal from all unvisited vertices:");
g.BFS();

Output
Following is Breadth First Traversal from all unvisited vertices:
0 1 2 3 

Time complexity: O(V+E).

Space complexity: O(V).


Next Article

Similar Reads