Technology3 min read

Breadth First Search or BFS for a Graph

Abhishek Ahlawat

By Abhishek Ahlawat — NOVEMBER 29, 2021

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#graph#bfs#algorithm

Summarize this article using AI

Breadth first search

In this lesson, you will learn about breadth first search method. Also, you will discover functioning examples of the bfs algorithm in Java.

Traversal means traversing all the nodes of a graph. Breadth First Traversal or Breadth First Search is a recursive algorithm for searching all the vertices of a graph or tree data structure.

BFS algorithm

A basic BFS implementation assigns each vertex of the graph into one of two categories:

  • Visited
  • Not Visited

The goal of the method is to label each vertex as visited while avoiding cycles.

The algorithm operates as follows:

  • Start by placing any one of the graph's vertices to the rear of a queue.
  • Take the front item in the queue and add it to the visited list.
  • Create a list of that vertex's nearby nodes. Add the ones which aren't on the visited list to the rear of the queue.
  • Keep repeating steps 2 and 3 until the line is empty.

The network can have two separate unconnected pieces therefore to make sure that we cover every vertex, we can additionally perform the BFS algorithm on every node

BFS example

Let's explore how the Breadth First Search algorithm works using an example. We utilize an undirected graph with 5 vertices.

bfs

We start with vertex 0, the BFS algorithm begins by placing it in the Visited list and putting all its adjacent vertices in the stack.

bfs

Next, we visit the element at the head of the queue i.e. 1 and move to its adjacent nodes. Since 0 has already been visited, we visit 2 instead.

bfs

Vertex 2 has an unvisited neighbouring vertex in 4, so we add it to the rear of the queue and visit 3, which is at the top of the line.

bfs

Only 4 remains in the queue as the only nearby node of 3 i.e. 0 is already visited. We visit it.

bfs

Since the queue is empty, we have finished the Breadth First Traversal of the graph.

BFS Pseudocode

create a queue Q 
mark v as visited and put v into Q 
while Q is non-empty 
    remove the head u of Q 
    mark and enqueue all (unvisited) neighbours of u

Java Code Example

The code for the Breadth First Search Algorithm with an example is presented below. The code has been streamlined so that we may concentrate on the algorithm rather than extraneous aspects.

// BFS algorithm in Java

import java.util.*;

public class Graph {
  private int V;
  private LinkedList<Integer> adj[];

  // Create a graph
  Graph(int v) {
    V = v;
    adj = new LinkedList[v];
    for (int i = 0; i < v; ++i)
      adj[i] = new LinkedList();
  }

  // Add edges to the graph
  void addEdge(int v, int w) {
    adj[v].add(w);
  }

  // BFS algorithm
  void BFS(int s) {

    boolean visited[] = new boolean[V];

    LinkedList<Integer> queue = new LinkedList();

    visited[s] = true;
    queue.add(s);

    while (queue.size() != 0) {
      s = queue.poll();
      System.out.print(s + " ");

      Iterator<Integer> i = adj[s].listIterator();
      while (i.hasNext()) {
        int n = i.next();
        if (!visited[n]) {
          visited[n] = true;
          queue.add(n);
        }
      }
    }
  }

  public static void main(String args[]) {
    Graph 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);

    System.out.println("Following is Breadth First Traversal " + "(starting from vertex 2)");

    g.BFS(2);
  }
}

BFS Algorithm Complexity

The temporal complexity of the BFS algorithm is written in the form of O(V + E), where V is the number of nodes and E is the number of edges.

The space complexity of the algorithm is O(V).

BFS Algorithm Applications

  • To construct index via a search index
  • For Gps tracking finding algorithms
  • In the Ford-Fulkerson method to discover maximum flow in a network
  • Cycle detection in an undirected graph
  • In minimal spanning tree

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops — put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next