📖 Scenario: You are exploring a small network of connected cities. Each city is connected to some other cities by roads. You want to visit all cities starting from a specific city, exploring neighbors first before going deeper.
🎯 Goal: Build a program that uses BFS (Breadth First Search) to visit all cities in the network starting from a given city and print the order of visiting.
📋 What You'll Learn
Create a graph using a map where keys are city names (strings) and values are slices of connected city names.
Create a queue to help with BFS traversal.
Implement BFS using a queue and a visited map to avoid revisiting cities.
Print the order of cities visited by BFS starting from a given city.
💡 Why This Matters
🌍 Real World
BFS is used in social networks to find friends nearby, in maps to find shortest paths, and in many network and web crawling tasks.
💼 Career
Understanding BFS is essential for software engineers working on graph problems, search algorithms, and network analysis.
Progress0 / 4 steps
1
Create the graph data structure
Create a variable called graph of type map[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 Go
Hint
Use a map with string keys and slice of strings as values to represent the graph connections.
2
Create a queue and visited map for BFS
Create a variable called queue as a slice of strings initialized with "A". Create a variable called visited as a map of string to bool, and mark "A" as visited.
DSA Go
Hint
Initialize the queue with the starting city "A" and mark it visited in the map.
3
Implement BFS traversal loop
Use a for loop that runs while len(queue) > 0. Inside the loop, remove the first element from queue into a variable current. For each neighbor in graph[current], if it is not visited, append it to queue and mark it visited.
DSA Go
Hint
Use a loop to process the queue until empty. Remove the first city, then add unvisited neighbors to the queue and mark them visited.
4
Print the BFS visiting order
Create a slice of strings called order before the loop. Inside the BFS loop, append current to order. After the loop ends, print order.
DSA Go
Hint
Keep track of the visiting order by appending each visited city to a slice, then print it after BFS completes.
Practice
(1/5)
1. What is the main purpose of BFS (Breadth First Search) on a graph?
easy
A. To sort nodes in descending order
B. To find the shortest path using depth-first traversal
C. To explore all nodes level by level starting from a source node
D. To find cycles in a graph using recursion
Solution
Step 1: Understand BFS traversal
BFS explores nodes by visiting all neighbors of a node before moving to the next level.
Step 2: Compare BFS with other traversals
Unlike DFS, BFS uses a queue to explore nodes level by level, which helps in shortest path problems.
Final Answer:
To explore all nodes level by level starting from a source node -> Option C
Quick Check:
BFS = Level-wise exploration [OK]
Hint: BFS uses a queue to explore nodes level by level [OK]
Common Mistakes:
Confusing BFS with DFS
Thinking BFS uses recursion
Assuming BFS sorts nodes
2. Which of the following Go code snippets correctly initializes a queue for BFS traversal?
easy
A. queue := []int{} // empty slice as queue
B. queue := make(map[int]bool) // map as queue
C. queue := 0 // integer as queue
D. queue := make(chan int) // channel as queue
Solution
Step 1: Identify data structure for BFS queue
BFS requires a FIFO structure; a slice can be used as a queue in Go.
Step 2: Check each option
queue := []int{} // empty slice as queue uses a slice which can enqueue and dequeue elements. queue := make(map[int]bool) // map as queue is a map, not suitable as queue. queue := 0 // integer as queue is an int, not a queue. queue := make(chan int) // channel as queue is a channel, which can be used but requires goroutines and is complex.
Final Answer:
queue := []int{} // empty slice as queue -> Option A
Quick Check:
Slice as queue = queue := []int{} // empty slice as queue [OK]
Hint: Use slice for queue in BFS, not map or int [OK]
Common Mistakes:
Using map instead of slice for queue
Using int variable as queue
Confusing channels with simple queue
3. What is the output of the following Go BFS traversal code on the graph below?
4. Identify the bug in the following BFS Go code snippet and select the correct fix.
func bfs(graph map[int][]int, start int) []int {
visited := make(map[int]bool)
queue := []int{start}
order := []int{}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
order = append(order, node)
for _, neighbor := range graph[node] {
if !visited[neighbor] {
queue = append(queue, neighbor)
visited[neighbor] = true
}
}
}
return order
}
medium
A. Mark start node as visited before loop
B. Initialize order slice with capacity
C. Use a stack instead of queue
D. Remove visited map entirely
Solution
Step 1: Check visited marking for start node
The code never marks the start node as visited before starting, so it may revisit it.
Step 2: Fix by marking start visited before loop
Adding visited[start] = true before the loop prevents revisiting the start node and infinite loops.
Final Answer:
Mark start node as visited before loop -> Option A
Quick Check:
Start visited before loop = Mark start node as visited before loop [OK]
Hint: Always mark start visited before BFS loop [OK]
Common Mistakes:
Marking visited after enqueue
Using stack instead of queue
Ignoring visited map
5. Given a directed graph represented as adjacency list, how can BFS be adapted to find the shortest path length from a start node to a target node? Choose the best approach.
hard
A. Use BFS but enqueue nodes multiple times to find shortest path
B. Use DFS and backtrack to find all paths, then pick shortest
C. Use BFS but ignore visited nodes to explore all paths
D. Use BFS with a distance map to track levels from start, stop when target found
Solution
Step 1: Understand BFS for shortest path
BFS explores nodes level by level, so the first time target is reached is the shortest path.
Step 2: Use a distance map to track levels
Maintain a map to record distance from start for each node. When target is dequeued, return its distance.
Final Answer:
Use BFS with a distance map to track levels from start, stop when target found -> Option D
Quick Check:
BFS + distance map = shortest path [OK]
Hint: Track distance in BFS, stop at target [OK]
Common Mistakes:
Using DFS for shortest path in unweighted graph
Ignoring visited nodes causing infinite loops
Enqueuing nodes multiple times unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.