Grids are graphs
Each square cell is a node. Its neighbours are the cells directly up, down, left and right: those are its edges. Every move costs 1, so breadth-first search (BFS) finds the fewest moves from a start cell.
Now there are two sources, A and B, like two exits. For every cell we want the moves to the NEAREST one. Running BFS from A, then again from B, and keeping the smaller answer works, but costs two full passes.
Many sources at once
Multi-source BFS does it in one pass. Before the loop, put every source in the queue and give each distance 0. A queue is first in, first out: append adds at the back, popleft takes from the front.
Pop A from the front: its two new neighbours get distance 1 and join the back. Pop B: the same. The queue now holds only 1s, so every cell one move from either source is handled before any cell two moves away.
Popping the 1s labels the 2s. A neighbour that already has a number is skipped, so no cell is labelled twice. When the A wave and the B wave touch, a cell keeps the first number it gets: the one from the nearer source.
The queue empties. Every cell holds its moves to the nearest source, at most 3 here. Each of the 20 cells went in and out of the queue once, so the cost is O(V + E), the same as one BFS.
Moves that cost 0 or 1
New question. Walls rise; you may break through one for a cost of 1. Stepping onto an open cell costs 0. What is the fewest walls to break from A to each cell? Plain BFS counts moves, not walls, so it gives wrong answers.
Use a deque, a queue you can add to at both ends. Pop A. Its open neighbours cost 0 more, so appendleft puts them at the FRONT, ahead of everything. A move onto a wall costs 1, so append puts it at the back.
Keep popping the front. The deque only ever holds two values, d at the front and d + 1 behind, so cells come out in order of walls broken: every 0, then every 1, then every 2, B among them.
Done: B shows 2, so the best route from A to B breaks 2 walls. Like plain BFS, 0-1 BFS runs in O(V + E) time, with no heap like Dijkstra's algorithm needs.
What happens
;; step 1/10 · grid-graph grid: 4 rows × 5 columns = 20 cells (nodes) neighbours of (r, c): (r-1, c) (r+1, c) (r, c-1) (r, c+1) edges: 4·4 across + 3·5 down = 31 neighbour pairs BFS on a graph with V nodes and E edges: O(V + E)
BFS is correct because the queue hands out cells in order of distance: all the 0s, then all the 1s, then all the 2s. Starting with every source at 0 keeps that order, so the first label a cell gets is its distance to the nearest source. In 0-1 BFS a cell can be put in the deque more than once if a cheaper route turns up later. The old copy is harmless: when it is popped, no neighbour improves. Popping a cell, then, never lowers a distance that is already final.