countEnclosedRegions function

int countEnclosedRegions(
  1. Artifact grid
)

Counts the number of enclosed regions in a given grid.

An enclosed region is a contiguous area of false cells completely surrounded by true cells. This is useful for character recognition: e.g. 'O' has one enclosed region, 'B' has two.

Implementation

int countEnclosedRegions(final Artifact grid) {
  final int rows = grid.rows;
  final int cols = grid.cols;

  final Artifact visited = Artifact(cols, rows);

  int loopCount = 0;

  for (int y = 0; y < rows; y++) {
    for (int x = 0; x < cols; x++) {
      if (!grid.cellGet(x, y) && !visited.cellGet(x, y)) {
        int regionSize = _exploreRegion(grid, visited, x, y);
        if (regionSize >= _minEnclosedRegionSize &&
            _isEnclosedRegion(grid, x, y, regionSize)) {
          loopCount++;
        }
      }
    }
  }

  return loopCount;
}