C/C++ Arena

Step 2 of 6

Shortest path with BFS

When every edge has the same cost, breadth-first search finds shortest paths: it explores everything 1 step away, then 2 steps, and so on, so the first time it reaches a cell is by a shortest route.

Grids are graphs too: each open cell is a vertex connected to its up/down/left/right neighbors.

dist[start] = 0; queue = [start]
while queue not empty:
    cur = pop front
    for each open neighbor nb with no dist yet:
        dist[nb] = dist[cur] + 1; push nb

Your turn: write int shortest_path(const std::vector<std::string>& grid) returning the fewest moves from S to E, moving through . cells (not #), or -1 if E can't be reached.

Previous: Adjacency lists Next: Depth-first flood fill