Graph Theory37 sections · 1633 units
Open in Course

The BFS Algorithm Step 3

The Loop

The BFS loop runs while the queue is not empty:

while queue is not empty:
    u = queue.pop_front()
    for each neighbor v of u:
        if not visited[v]:
            visited[v] = true
            dist[v] = dist[u] + 1
            queue.push_back(v)

Each iteration removes the front node uu from the queue. Examine every neighbor vv of uu. If vv is already visited, skip it. If vv is unvisited, mark it visited, set dist[v] to dist[u] + 1, and add vv to the queue.

Repeat until the queue is empty. The distance array now holds the shortest distance to each node.