You could run BFS from each cell to find the nearest .
But if there are cells with , you'd run BFS times. That's , which can time out.
Instead, reverse the problem. Push all cells into the queue at distance . Then run BFS once. As you spread outward, you discover cells at distance , then cells at distance , and so on.
Why does this work? Because BFS explores in order of increasing distance. The first time you reach a cell from any cell, that's the shortest distance. You never need to revisit it.