<> wrote
> Can someone help me with C programming here.
> If I have
> x is a 2D array of 0's and 1's
> ex: x = array([1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0],
> [1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,0,0,0],
> [1,1,1,0,1,1,1,0,1,1,0,1,1,1,0,0,0,0],
> [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0])
> what I want is a boundingbox over the region where we find clusters of
> 1's.So for instance in the above list first 3 roes and colums have 1's
> so the area of that box is 3x3
> so my final array should have an array of clusters of
> 1's like
> coords = [ (x1,y1,x2,y2), ....]
> where x1,y1 -> top left point
> x2,y2 -> bottom right point of that rectangle.
> Hope I am clear with my question.
>
> [0, 0, 0, 0, 0,
> +-----+
> 0,|1, 1,|0, 0,
> | |
> 0,|0, 1,|0, 0,
> +-----+
> 0, 0, 0, 0, 0]
>
> something like above. The resultant array should have the area of the
> each such box. SOmething like a flood fill algorithm.
> I would like the algorithm to return all the rectangles .Not just the
> minimum ones.
>
First thing to do is to allocate a temporary array of integers. Set the ones
to one and the zeroes to zero.
Then iterate over the array. When you hit a one, do a flood fill, filling
with 2, 3, 4 etc, like this
void floodfill(int * array, int x, int y, int width, int height, int fill)
{
if(x < 0 || x >= width)
return;
if(y < 0 || y >= height)
return;
if(array[y * width + x] == fill)
return;
if(array[y * width + x] == 0)
return;
array[y * width + x] = fill;
floodfill(array, x + 1, y, width, height, fill);
floodfill(array, x - 1, y, width, height, fill);
floodfill(array, x, y + 1, width, height, fill);
floodfill(array, x, y -1, width, height, fill);
}
The resulting array should be a list of zeroes, and clusters from 2 up. Also
keep a count of how many clusters you have found.
Now allocate an array of rectangle structures, and an array of flags. Set
all the falgs to zero.
Iterate over the array a second time. When you hit a non-zero, check the
flag. If it is clear, you have the top point of the cluster. If the array is
relatively small and time isn't critical, it is probably easiest to iterate
from the top left going down columns to find the left point, to iterate from
the bottom up to find the bottom point, and from the right going up columns
to find the right point.
(If you have a huge array with small clusters you can search the cluster
using the floodfill again, and store maximum and minimum points).
Then set the flag to mark the fact that you have found the rectnagle for
that cluster, and continue until you reach the end of the array.