How to Implement BFS? | Part 2

By Prajwal Haniya

Techletter #26 | May 20, 2023

As BFS is based on queue let’s first understand how to implement a queue in JavaScript

// program to implement a queue data structure
class Queue {
    constructor() {
        this.queue = [];
    }
   
    enqueue(element) { // add element
        return this.queue.push(element);
    }
    
    dequeue() { 
        if(this.queue.length > 0) {
            return this.queue.shift();   // remove first element
        }
    }
    
    peek() {
        return this.queue[this.queue.length - 1];
    }
      
    size(){
        return this.queue.length;
    }

    isEmpty() {
       return this.queue.length == 0;
    }

    clear(){
        this.queue = [];
    }
}

let counter =  new Queue();

// add
counter.enqueue(1);
counter.enqueue(2);
counter.enqueue(3);

// get last element 
console.log(counter.peek()); // 3

// remove
console.log(counter.dequeue()); // 1
console.log(counter.dequeue()); // 2

console.log(counter.isEmpty()); // false
console.log(counter.size()); // 1

counter.clear(); 
console.log(counter.size()); // 0

The above code helps you implement a queue. And helps you understand enqueue and deque.

I expect that you already understand JavaScript and are comfortable coding in it. So, I am not explaining the above code line by line.

Now let’s implement and understand BFS implementation.

class Node {
    constructor(value) {
        this.value = value;
        this.neighbors = [];
    }

    addNeightbors(neighbor) {
        this.neighbors.push(neighbor);
    }
}

The above class represents a node, where each node has a value and an array of neighbors.\

function bfs(startNode) {
    const queue = [];
    const visited = new Set();

    queue.push(startNode);
    visited.add(startNode);

    while (queue.length > 0) {
        const currentNode = queue.shift()
        // print the visited node
        console.log(currentNode);
        for (let i = 0; i < currentNode.neighbors.length; i++) {
            const neighbor = currentNode.neighbors[i];
            if (!visited.has(neighbor)) {
                queue.push(neighbor);
                visited.add(neighbor);
            }
        }
    }
}

If you walk through the above code multiple times you will understand the code, as there is not much complexity in it.