To find the number of rectangular blocks in a matrix where block is the one having same numbers

#include <stdio.h>

/*
 * Algorithm:
 *
 * 1. Visit all the elements row by row
 * 2. Compare the value of the current element with the values of the above and left of the current element
 * 3. If it is equal to atleast one of them, don't increment numblocks
 * Otherwise increment numblocks
 *
 *
 */

int numBlocks(int m, int n, int (*a)[3]){


int i, j;

int numblocks = 0;



for(i = 0 ; i < m; ++i){

for(j = 0 ; j < n; ++j){

if(i - 1 >= 0 && a[i - 1][j] == a[i][j]) continue;

if(j - 1 >= 0 && a[i][j - 1] == a[i][j]) continue;
            if(i - 1 >= 0 && j + 1 < n && a[i - 1][j + 1] == a[i][j]  && a[i][j+1] == a[i][j]) continue;

numblocks++;

}
}


return numblocks;


}


int main(){

int a[][3] = {
{1, 1, 1},
{1, 1, 3},
{4, 4, 5}
};

printf("%d\n", numBlocks(3, 3, a));

}
Advertisements

One thought on “To find the number of rectangular blocks in a matrix where block is the one having same numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s