我需要找到矩阵中有多少个区域和多少个元素。矩阵用0和1填充。如果有相邻的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;
}