Grid BFS (Maze/Flood Fill)

Concept

Grid BFS applies BFS on a 2D grid using 4-directional movement (up, down, left, right). It finds the shortest distance from a source cell to all reachable cells. Each cell is treated as a graph node with edges to its 4 neighbors.

When to Use

  • Shortest path in a maze or grid
  • Flood fill (spreading from a source)
  • Finding minimum steps to reach a target cell
  • Any grid problem where all moves have equal cost

Intuition

Picture water flooding from a starting cell. Each second, it spreads one step in all 4 directions. Cells closer to the source get flooded first. The distance array records when each cell gets reached — that's the shortest distance. Walls or blocked cells simply stop the water.

Complexity

Time
O(M * N)
Space
O(M * N)

Template Code

cpp
#include<bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(0), cin.tie(0);

    int m, n;
    cin >> m >> n;

    vector<vector<int>> mp(m, vector<int>(n));
    for(int i = 0; i < m; i++)
        for(int j = 0; j < n; j++)
            cin >> mp[i][j];

    queue<pair<int, int>> q;
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};

    const int inf = 1e9+7;
    vector<vector<int>> dist(m, vector<int>(n, inf));

    int rs = 0, cs = 0; // start position
    dist[rs][cs] = 0;
    q.push({rs, cs});

    while(!q.empty()){
        int r = q.front().first;
        int c = q.front().second;
        q.pop();

        for(int d = 0; d < 4; d++){
            int nr = r + dx[d];
            int nc = c + dy[d];

            if(nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
            if(mp[nr][nc] == 0) continue;
            if(dist[nr][nc] != inf) continue;

            dist[nr][nc] = dist[r][c] + 1;
            q.push({nr, nc});
        }
    }

    return 0;
}

// Sample Input:
// 4 4
// 1 1 1 1
// 1 0 0 1
// 1 1 1 1
// 0 0 1 1
//
// dist from (0,0):
// 0 1 2 3
// 1 . . 4
// 2 3 4 5
// . . 5 6