在矩阵c ++中查找区域

时间:2014-11-03 20:20:12

标签: c++ matrix

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

1 个答案:

答案 0 :(得分:0)

尝试查看connected components labelling算法。