シンプルで高速なアルゴリズムの1つは、すべてのエントリを反復処理し、検出されたときに各領域をゼロに設定することです。これには、O(N * M)ランタイム(各エントリが最大2回アクセスされる)とO(1)追加メモリが必要です。
領域をゼロに設定するには、領域が始まる列に注意してから、右端の列まで繰り返します。次に、下の行を左から右の列まで繰り返し、各エントリをゼロに設定します。
作業コード:
int count_regions( int *arr, int rows, int cols ) {
int region_count = 0;
for ( int first_index = 0; first_index != rows * cols; ++ first_index ) {
if ( arr[ first_index ] == 0 ) continue;
++ region_count;
int first_row = first_index / cols, first_col = first_index % cols;
int last_col;
for ( last_col = first_col;
last_col != cols && arr[ first_row * cols + last_col ] != 0;
++ last_col ) ;
for ( int last_row = first_row;
last_row != rows && arr[ last_row * cols + first_col ] != 0;
++ last_row ) {
for ( int col = first_col; col != last_col; ++ col ) {
arr[ last_row * cols + col ] = 0;
}
}
}
return region_count;
}