← All Exercises

Graph Breadth-First Search

advancedjavascript~30min

Background

BFS is used in shortest path finding on unweighted graphs, web crawling, and social network analysis.

Problem

Write a function that performs BFS on a graph starting from a given node, returning the visited nodes in BFS order.

Input

A graph as an adjacency list object and a starting node.

Output

An array of node values in the order they were visited.

Sample tests

Sample 1

Input: {A:["B","C"], B:["D"], C:["D"], D:[]}, start="A"
Expected: ["A","B","C","D"]

Your solution

Learning objective

Understand BFS traversal order, queue-based processing, and cycle prevention with visited sets.