Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

BFS Traversal

Easy Acceptance 83.12% Points 20.00

You are given a graph with V vertices and its adjacency list. Starting from vertex 0, perform a Breadth First Search (BFS) traversal and return the order in which the vertices are visited.

BFS visits vertices level by level, exploring all neighboring vertices before moving to the next level.

Examples
Example 1

image Input: V = 5, adj = [[1,2],[0,3],[0,4],[1],[2]]
Output: [0,1,2,3,4]
Explanation: The vertices are visited level by level starting from vertex 0.

Example 2

image Input: V = 3, adj = [[1],[0,2],[1]]
Output: [0,1,2]
Explanation: BFS visits the graph level by level.

Example 3

image Input: V = 1, adj = [[]]
Output: [0]
Explanation: The graph contains only one vertex.

Constraints
    • 1 = V = 105
    • 0 = E = 2 × 105
Companies
Airbnb PhonePe
Topics
Graph
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions