📖 Scenario: Imagine you have a map of cities connected by roads. You want to visit all cities starting from one city, exploring neighbors first before going deeper. This is like spreading out in waves, visiting all nearby cities before moving further.
🎯 Goal: You will build a program that uses BFS (Breadth First Search) to visit all nodes in a graph starting from a given node, and print the order of visited nodes.
📋 What You'll Learn
Create a graph using an adjacency list representation
Use a queue to manage nodes to visit in BFS order
Keep track of visited nodes to avoid repeats
Print the order of nodes visited by BFS
💡 Why This Matters
🌍 Real World
BFS is used in social networks to find friends within certain distances, in GPS navigation to find shortest paths, and in web crawlers to explore websites layer by layer.
💼 Career
Understanding BFS is essential for software engineers working on search algorithms, network analysis, and game development where exploring connected components efficiently is needed.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a constant called graph as a Record<string, string[]> with these exact entries: 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'].
DSA Typescript
Hint
Use a TypeScript object where keys are city names and values are arrays of connected cities.
2
Set up BFS helper variables
Create a constant startNode and set it to 'A'. Create a variable visited as a Set<string> and add startNode to it. Create a variable queue as an array of strings initialized with startNode. Create a variable order as an empty array of strings to store the visit order.
DSA Typescript
Hint
Initialize visited as a Set and add the start node. Use an array queue starting with the start node. Prepare an empty array order to record the visit sequence.
3
Implement BFS loop to visit nodes
Write a while loop that runs while queue.length > 0. Inside the loop, remove the first element from queue into a variable current. Add current to the order array. Then, use a for loop with variable neighbor to iterate over graph[current]. Inside this loop, if neighbor is not in visited, add it to visited and push it to queue.
DSA Typescript
Hint
Use queue.shift() to get the current node. Add it to order. Check neighbors and add unvisited ones to visited and queue.
4
Print the BFS visit order
Write console.log(order.join(' -> ')) to print the order of nodes visited by BFS separated by arrows.
DSA Typescript
Hint
Use console.log(order.join(' -> ')) to show the BFS visit order clearly.
Practice
(1/5)
1. What does BFS (Breadth First Search) primarily use to keep track of nodes to visit next in a graph?
easy
A. A priority queue to select nodes by weight
B. A stack to process nodes in depth order
C. A hash map to store visited nodes only
D. A queue to process nodes level by level
Solution
Step 1: Understand BFS traversal method
BFS explores nodes level by level, so it needs a structure that processes nodes in the order they are discovered.
Step 2: Identify the data structure used
A queue follows First-In-First-Out (FIFO) order, which matches BFS's level order traversal.
Final Answer:
A queue to process nodes level by level -> Option D
Quick Check:
BFS uses a queue = A [OK]
Hint: BFS uses FIFO order, so it needs a queue [OK]
Common Mistakes:
Confusing BFS with DFS which uses a stack
Thinking BFS uses a priority queue
Assuming BFS only uses a visited set without a queue
2. Which of the following is the correct TypeScript syntax to initialize a queue for BFS using an array?
easy
A. const queue = new Queue<number>();
B. const queue: number[] = [];
C. let queue = {};
D. var queue = new ArrayQueue();
Solution
Step 1: Recognize TypeScript array initialization
To create a queue using an array, declare an array with type annotation and initialize it empty.
Step 2: Check each option
const queue: number[] = []; correctly declares an empty number array. const queue = new Queue<number>(); uses a class Queue which is not built-in. let queue = {}; initializes an object, not a queue. var queue = new ArrayQueue(); uses a non-existent ArrayQueue.
Final Answer:
const queue: number[] = []; -> Option B
Quick Check:
Array queue syntax = A [OK]
Hint: Use typed empty array for queue in TypeScript [OK]
Common Mistakes:
Using undefined classes like Queue without import
Initializing queue as an object {} instead of array
Using var instead of const or let (less preferred)
3. Given the graph adjacency list below and BFS starting from node 0, what is the order of nodes visited?