Course lesson

Breadth First JavaScript Search Algorithm for Graphs

Breadth first search is a graph search algorithm that starts at one node and visits neighboring nodes as widely as possible before going further down any other path. This algorithm requires the use of a queue to keep track of which nodes to visit, so it might...

Duration
2 min
Access
Pro
Transcript
Available

Breadth first search is a graph search algorithm that starts at one node and visits neighboring nodes as widely as possible before going further down any other path. This algorithm requires the use of a queue to keep track of which nodes to visit, so it might be worth your time to brush up on that data structure before watching this lesson.

Summary

Breadth first search algorithm

Breadth first search is an algorithm we can use to traverse all nodes in a graph. It starts at one node and visits all of that node's neighbors before moving on to the next node's neighbors. This is what the "Breadth" in the name implies, as it will visit widely across a node's neighbors, before traversing the edges of a neighboring node.

Use cases

  • Finding the shortest path from one node to another - Google Maps
  • Crawlers for search engines - Google

Implementation

graphs/breadthFirstSearch.js

{
  // rest of graph from previous lesson
  breadthFirstSearch(startingNodeKey, visitFn) {
    const startingNode = this.getNode(startingNodeKey)

    const visited = nodes.reduce((acc, node) => {
      acc[node.key] = false
      return acc
    }, {})

    const queue = createQueue()
    queue.enqueue(startingNode)

    while (!queue.isEmpty()) {
      const currentNode = queue.dequeue()

      if (!visited[currentNode.key]) {
        visitFn(currentNode)
        visited[currentNode.key] = true
      }

      currentNode.neighbors.forEach(node => {
        if (!visited[node.key]) {
          queue.enqueue(node)
        }
      })
    }
  }
}

✏️ Edit on GitHub