Graph Theory37 sections · 1633 units
Open in Course

Tracking Distances

The Distance Array

Instead of a separate visited array, use the distance array for both purposes:

dist = [infinity] * (n + 1)
dist[s] = 0
queue.push_back(s)

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

Initialize all distances to infinity. Set dist[s] to 00 for the source. When you visit a node vv, set dist[v] to dist[u] + 1. If a node's distance is still infinity, it has not been visited. This saves memory and makes the code cleaner. After BFS finishes, dist[v] tells you the shortest path length to vv. If dist[v] is still infinity, vv is unreachable from the source.