Sobes.tech
Middle

What is a breadth-first search algorithm?

sobes.tech AI

Answer from AI

Breadth-First Search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at a root node (or arbitrary node in a graph) and explores all its neighbors, then moves to their neighbors, and so on, level by level. BFS is implemented using a queue.

How it works:

  1. Enqueue the starting node.
  2. While the queue is not empty:
    • Dequeue a node.
    • If it is the target, stop.
    • Otherwise, enqueue all its unvisited neighbors and mark them as visited.

Characteristics:

  • Completeness: Guarantees to find a solution if one exists.
  • Optimality: Finds the shortest path in an unweighted graph.
  • Time complexity: O(V + E), where V is vertices and E is edges.
  • Space complexity: O(V), for storing visited nodes and the queue.

Application in QA:

  • Finding shortest path between nodes in test scenarios.
  • Exploring all reachable states in system testing.
  • Web crawling to verify accessibility of all pages.

Example (tree traversal):

from collections import deque

# Example adjacency list representation
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

def bfs(graph, start_node):
    visited = set()
    queue = deque([start_node])
    visited.add(start_node)

    while queue:
        node = queue.popleft()
        print(node)

        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

# Example call
# bfs(graph, 'A')
# Output:
# A
# B
# C
# D
# E
# F
What is a breadth-first search algorithm? — QA / QA… - sobes.tech