Connected Cells in a Grid

  • + 0 comments

    c++ using bfs (breath first search) approach

    define pii pair

    define mk make_pair

    int bfs(int r, int c, vector> &mat, vector> &vis, int n, int m) { int surf = 0; queue q; q.push(mk(r,c)); // cout << "starting " << r << " "<

    pii cur;
    while (!q.empty()) {
        cur = q.front();
        int cr = cur.first;
        int cc = cur.second; 
        q.pop();
    
        if (!vis[cr][cc]) {
            vis[cr][cc]=true;
            // cout << "visiting " << cr << " " << cc << '\n';
            surf++;
    
            if (cr-1 >= 0) {
                if (mat[cr-1][cc]) q.push(mk(cr-1,cc));
    
                if (cc-1 >= 0 and mat[cr-1][cc-1]) q.push(mk(cr-1,cc-1));
    
                if (cc+1 < m and mat[cr-1][cc+1]) q.push(mk(cr-1,cc+1));
            }
            if (cr+1 < n) {
                if (mat[cr+1][cc]) q.push(mk(cr+1,cc));
    
                if (cc-1 >= 0 and mat[cr+1][cc-1]) q.push(mk(cr+1,cc-1));
    
                if (cc+1 < m and mat[cr+1][cc+1]) q.push(mk(cr+1,cc+1));
            }
            if (cc-1 >= 0) {
                if (mat[cr][cc-1]) q.push(mk(cr,cc-1));
    
                // if (cr-1 >= 0 and mat[cr-1][cc-1]) q.push(mk(cr-1,cc-1));
    
                // if (cr+1 < m and mat[cr+1][cc+1]) q.push(mk(cr+1,cc+1));
            }
            if (cc+1 < m) {
                if (mat[cr][cc+1]) q.push(mk(cr,cc+1));
    
                // if (cr-1 >= 0 and mat[cr-1][cc+1]) q.push(mk(cr-1,cc+1));
                // 
                // if (cc+1 < m and mat[cr-1][cc+1]) q.push(mk(cr-1,cc+1));
            }
        }
    }
    
    return surf;
    

    }

    int connectedCell(vector> matrix) { int n = matrix.size(), m = matrix[0].size(); vector> vis(n, vector(m,false));

    int res = 0;
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] and !vis[i][j]) {
                res = max(res,bfs(i,j,matrix,vis,n,m));
            }
        }
    }
    return res;
    

    }