Finding the existence of an enclosed space within a 2D M x N grid
The idea is:
- we start from every non-visited empty cell
- try to visit all connected empty cells
- if we can go to the boundary then this is not an enclosed area
- if no cell of the connected region is boundary cell then the region is enclosed by wall and we increment the count.
Here is sample implementation in c++
that count the number of enclosed area:
#include <string.h>
#include <cstdio>
// m is row_num, n is column_num
int m, n;
// grid
char grid[5005][5005];
// direction arrays
int R[] = {0, -1, 0, 1};
int C[] = {1, 0, -1, 0};
// check for weather we reach boundary or not
// and visit array
bool wentToBoundary, vis[5005][5005];
// DFS implementation of 2D grid
void dfs(int x, int y) {
// visit the cell grid[x][y] as true
vis[x][y] = true;
// if the current cell is a boundary cell, then mark that
// we reach to boundary from an inner cell
if (x == 0 || x == m -1 || y == 0 || y == n - 1)
wentToBoundary = true;
// try to go in all 4 direction (right, up, left, down)
// if the cell is not visited yet and contains ' '
for (int i = 0; i < 4; i++) {
int xx = x + R[i];
int yy = y + C[i];
if (xx >=0 && xx < m && yy >= 0 && yy < n) {
if (!vis[xx][yy] && grid[xx][yy] == ' ')
dfs(xx, yy);
}
}
}
int main() {
// input the grid size;
scanf("%d %d", &m, &n);
getchar();
// input the grid
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%c", &grid[i][j]);
}
getchar();
}
// initialize
int spaceEnclosedCount = 0;
memset(vis, false, sizeof(vis));
// iterate only for inner cells not the boundary cells
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < n - 1; j++) {
if (!vis[i][j] && grid[i][j] == ' ') {
wentToBoundary = false;
dfs(i, j);
if (!wentToBoundary) {
spaceEnclosedCount++;
}
}
}
}
printf("number of area enclosed by spaces: %d\n", spaceEnclosedCount);
return 0;
}