Compute the number of connected component in a matrix, saying M. Given two items with coordinates [x1, y1] and [x2, y2] in M,
M(x1, y1) == -1 && M(x2, y2) == -1 && |x1-x2|+|y1-y2|=1 <=> they are connected
Example:
-1 0 -1 0 0
-1 -1 0 -1 -1
0 0 0 0 -1
0 0 0 -1 -1
0 0 0 -1 0
0 -1 0 0 0
0 -1 0 0 0
Output: 4. And they are:
-1
-1 -1
-1
-1 -1
-1
-1 -1
-1
-1
-1
My idea is to scan the matrix.
Initialization:
count = 0.
For every item in the matrix, do the following three tests.
(1) If it's 0, skip
(2) If it's -1, check its four neighbors. If there is a neighbor whose value is not 0 and -1, assign the value of this neighbor to the current item. Otherwise,
count++, ant then assigncountto the current item.(3) If it's not 0 and -1, assign the value of current item to its four neighbors whose value is -1.
The following is my code:
int num_cc(int m[][COLS])
{
int count = 0;
int r;
int c;
for(r = 0; r < ROWS; ++r)
{
for(c = 0; c < COLS; ++c)
{
if(m[r][c] == 0)
continue;
if(m[r][c] == -1)
{
if(r-1>=0 && m[r-1][c] > 0)
m[r][c] = m[r-1][c];
else if(r+1<ROWS && m[r+1][c] > 0)
m[r][c] = m[r+1][c];
else if(c-1>=0 && m[r][c-1] > 0)
m[r][c] = m[r][c-1];
else if(c+1<COLS && m[r][c+1] > 0)
m[r][c] = m[r][c+1];
else
{
count++;
m[r][c] = count;
}
}
if(m[r][c] > 0)
{
if(r-1>=0 && m[r-1][c] == -1)
m[r-1][c] = m[r][c];
if(r+1<ROWS && m[r+1][c] == -1)
m[r+1][c] = m[r][c];
if(c-1>=0 && m[r][c-1] == -1)
m[r][c-1] = m[r][c];
if(c+1<COLS && m[r][c+1] == -1)
m[r][c+1] = m[r][c];
}
}
}
return count;
}
Can anyone help me verify it? Is it correct? Or is there any other solutions?
Thanks,