CodeBlanks Logo Icon CodeBlanks

Print the result

Print the reachable cities.

Print the result

In the final step we will print the BFS results. Combine all pieces: build_cities, add_neighbor and bfs_reachable.

This lesson uses all previous functions; the initial code chain is complete.

The output is the sorted list of reachable cities; deterministic and readable.

Project complete

This mini project combined the city graph, neighbor addition and BFS reachability.

In real applications similar structures are used in maps, routing and network analysis.

BFS is a fundamental tool for reachability; this project shows its practical use.

Practice Print the result

Write print_reachable(graph, start). Call bfs_reachable and print with print(). Output of print_reachable(build_cities(), "A"): ['A', 'B', 'C', 'D'].

Starter code

solution.py
def build_cities():
    # Define the city graph
    return {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"]}
def add_neighbor(graph, city, neighbor):
    # Add neighbor
    graph[city].append(neighbor)
    return graph
def bfs_reachable(graph, start):
    # Reachable cities
    visited = set()
    queue = [start]
    while queue:
        node = queue.pop(0)
        if node not in visited:
            visited.add(node)
            for nb in graph[node]:
                if nb not in visited:
                    queue.append(nb)
    return sorted(visited)
def print_reachable(graph, start):
    # Print result

Sample solution

solution.py
def build_cities():
    # Define the city graph
    return {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C"]}
def add_neighbor(graph, city, neighbor):
    # Add neighbor
    graph[city].append(neighbor)
    return graph
def bfs_reachable(graph, start):
    # Reachable cities
    visited = set()
    queue = [start]
    while queue:
        node = queue.pop(0)
        if node not in visited:
            visited.add(node)
            for nb in graph[node]:
                if nb not in visited:
                    queue.append(nb)
    return sorted(visited)
def print_reachable(graph, start):
    # Print result
    reachable = bfs_reachable(graph, start)
    print(reachable)
print_reachable(build_cities(), "A")

Expected output

['A', 'B', 'C', 'D']

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Print the result: match the terms

Term Meaning
print Print
reachable Reachable
sorted Sorted
BFS Discovery

2 Which structure was NOT used in this project?

  • Visited set
  • Graph
  • Queue
  • Heap Correct answer

Explanation: Heap.

3 Print

Question
print(____)
Answer
print(reachable)

Explanation: reachable is right.

All lessons in Intermediate