Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

BFS of a Graph Editorial

DSA Editorial, Solution and Code

Practice Problem Link: BFS of a Graph

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

Given a graph compute its BFS. The graph has n nodes indexed 0 to n-1. It is given in the form of an adjacency list. Return the BFS traversal starting at the node indexed 0. Follow the order of nodes as in the adjacency list.

Approach

The approach of BFS is to traverse to the nodes in a level-order manner. All the nodes at the current level get processed before the nodes at the level lower than them. We use a queue to implement BFS. First, we push the source into the queue. We will take the current node at the top of the queue and traverse its adjacency list. If the node is not visited, traverse over them and mark them as visited, and push these nodes into the queue before taking the next element from the top of the queue. Continue the process till the queue is empty and all the nodes are visited.

Analysis

  • Time Complexity: O(|V| + |E|)
  • Space Complexity: O(|V|)

Implementation

C++
vector<int> bfs(vector<vector<int>> adjList) {
    queue<int> queue;
	vector<int> traversal;
	vector<bool> isVisited (adjList.size(), false);
	if(adjList.size() == 0) {
		return traversal;
	}
	queue.push(0);
	isVisited[0] = true;
	for(int i = 0; i < adjList.size(); i++) {
		int node = queue.front();
		queue.pop();
		traversal.push_back(node);
		for(int j = 0; j < adjList[node].size(); j++) {
			if(isVisited[adjList[node][j]]) {
				continue;
			}
			queue.push(adjList[node][j]);
			isVisited[adjList[node][j]] = true;
		}
	}
	return traversal;
}
Java
class Solution {
    ArrayList<Integer> bfs(ArrayList<Integer>[] adjList) {
        Queue<Integer> queue = new LinkedList<Integer>();
		ArrayList<Integer> traversal = new ArrayList<Integer>();
		boolean[] isVisited = new boolean[adjList.length];
		if(adjList.length == 0) {
			return traversal;
		}
		queue.add(0);
		isVisited[0] = true;
		for(int i = 0; i < adjList.length; i++) {
			int node = queue.poll();
			traversal.add(node);
			for(int j = 0; j < adjList[node].size(); j++) {
				if(isVisited[adjList[node].get(j)]) {
					continue;
				}
				queue.add(adjList[node].get(j));
				isVisited[adjList[node].get(j)] = true;
			}
		}
		return traversal;
    }
}

 

Related Content
Adjacency List to Adjacency Matrix
Adjacency Matrix to Adjacency List
Capture Surrounded Regions
Clone a Graph
DFS of an Acyclic Graph
DFS of a Cyclic Graph
Edges to Adjacency List
Flood Fill Image
Knight's Journey On A Chessboard
M-Coloring Problem
Number of Islands
Stepping Numbers
Valid Path
Word Search Board
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet