#5

Use a search method, either breadth-first or depth-first.We use depth-first here, but the two are equivalent for this problem. Starting on the next blank pixel, search as if to reach a pixel which is not really reachable. Each pixel will get marked in the process. This counts as one connected region. Leave the marked pixels marked, and start on the next blank pixel. The next blank pixel can be found by a left-to-right, top-to-bottom, scan (raster scan). When the scan is complete, all regions have been counted.

  // countRegions returns the number of regions

  int countRegions()
    {
    // initialize marks

    for( int row = 0; row < gridHeight; row++ )
      for( int col = 0; col < gridWidth; col++ )
        marked[row][col] = false;

    int regions = 0;

    // raster scan for blank

    for( int row = 0; row < gridHeight; row++ )
      for( int col = 0; col < gridWidth; col++ )
        {
        if( !filled(row, col) && !marked[row][col] )
          {
          // search from blank unmarked square
          dfSearch(row, col);
          regions++;
          }
        }
    return regions;
    }

  void dfSearch(int row, int col)
    {
    if( filled(row, col) || marked[row][col] )
      return;
    marked[row][col] = true;
    dfSearch(row,   col+1);
    dfSearch(row+1, col  );
    dfSearch(row,   col-1);
    dfSearch(row-1, col  );
    }