在矩阵c++中查找区域

Find areas in matrix c++

本文关键字:查找 区域 c++      更新时间:2023-10-16

我需要找到矩阵中有多少区域和多少元素。矩阵中填充有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;
}

试着看看连接组件的标签算法。