DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question
  1. Home
  2. Tools
  3. Algorithm Visualizer
  4. Breadth-First Search

Breadth-First Search

Graphmedium#9

Explore level by level using a queue — finds shortest path

Ready

Step 1 of 0

Speed

Algorithm Code

1function bfs(grid, start, end) {
2 const queue = [start];
3 const visited = new Set();
4 visited.add(key(start));
5 while (queue.length > 0) {
6 const [r, c] = queue.shift();
7 if (r === end[0] && c === end[1]) return true;
8 for (const [dr, dc] of dirs) {
9 const nr = r+dr, nc = c+dc;
10 if (valid(nr,nc) && !visited.has(key(nr,nc))) {
11 visited.add(key(nr, nc));
12 queue.push([nr, nc]);
13 }
14 }
15 }
16 return false;
17}
Best

O(V + E)

Average

O(V + E)

Worst

O(V + E)

Space

O(V)

About Breadth-First Search

BFS explores all nodes at the current depth level before moving to nodes at the next depth level. It uses a queue (FIFO) and guarantees finding the shortest path in unweighted graphs. Essential for level-order traversal, shortest path, and connected components.

Time Complexity: Best: O(V + E), Average: O(V + E), Worst: O(V + E). Space: O(V).

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.