Assume I have a matrix something like this :
1 1 1 0 0 0
1 1 1 0 0 1
0 0 0 0 0 1
If two '1' are next to each other (horizontally and vertically only) and therefore belong to the same area. I need to find how many of these areas are there in a matrix. You can see that there's two areas of '1' in this matrix. I've been trying to solve this for hours now but the code gets really big and disgusting. Are there any algorithms out there I could adopt for this problem ?
If you don't really care about:
Keeping the input matrix intact
Performance and optimisations
then here's my take on this problem in C:
#include <stdio.h>
#define X 8
#define Y 4
#define IGN 1
int A[Y][X] = {
{ 1, 1, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 0, 1, 0, 1 },
{ 0, 0, 0, 0, 0, 1, 0, 1 },
{ 0, 0, 0, 0, 0, 1, 1, 1 },
};
int blank(int x, int y) {
if ((x < 0) || (x >= X) || (y < 0) || (y >= Y) || (A[y][x] == 0))
return 0;
A[y][x] = 0;
return 1 + blank(x - 1, y) + blank(x + 1, y) + blank(x, y - 1) + blank(x, y + 1);
}
int main() {
int areas = 0;
int i, j = 0;
for (i = 0; i < X; ++i)
for (j = 0; j < Y; ++j)
if (A[j][i] == 1)
if (blank(i, j) > IGN)
areas++;
printf("Areas: %i\n", areas);
return 0;
}
Once it encounters a 1
, it recursively expands over all neighbouring 1
elements, counting them and turning them into 0
. If the size of the area is larger than IGN
, then it is taken into account.
Notes:
If you need to keep the original matrix, you would have to use a copy for input.
If you plan on using this, you should probably turn this code into functions that get the array and its size from their parameters. Global variables and algorithm implementations in main()
should be avoided, but I made an exception in this case because it reduces the complexity of the code and allows the algorithm to be more clear.
With IGN
set to 1
, lone elements are not considered an area. Changing IGN
to 0
will get those too.
The if (A[j][i] == 1)
conditional in the loop is not strictly necessary, but it serves as a minor optimisation by avoiding unnecessary function calls, although compiler optimisations probably make it redudant.
You can easily modify this to get a listing of the elements in each area.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With