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:
Once it encounters a
1, it recursively expands over all neighbouring1elements, counting them and turning them into0. If the size of the area is larger thanIGN, 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
IGNset to1, lone elements are not considered an area. ChangingIGNto0will 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.