Find number of areas in a matrix -
assume have matrix :
1 1 1 0 0 0 1 1 1 0 0 1 0 0 0 0 0 1
if 2 '1' next each other (horizontally , vertically only) , therefore belong same area. need find how many of these areas there in matrix. can see there's 2 areas of '1' in matrix. i've been trying solve hours code gets big , disgusting. there algorithms out there adopt problem ?
if don't care about:
keeping input matrix intact
performance , optimisations
then here's take on 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; (i = 0; < x; ++i) (j = 0; j < y; ++j) if (a[j][i] == 1) if (blank(i, j) > ign) areas++; printf("areas: %i\n", areas); return 0; }
once encounters 1
, recursively expands on neighbouring 1
elements, counting them , turning them 0
. if size of area larger ign
, taken account.
notes:
if need keep original matrix, have use copy input.
if plan on using this, should turn code functions array , size parameters. global variables , algorithm implementations in
main()
should avoided, made exception in case because reduces complexity of code , allows algorithm more clear.with
ign
set1
, lone elements not considered area. changingign
0
too.the
if (a[j][i] == 1)
conditional in loop not strictly necessary, serves minor optimisation avoiding unnecessary function calls, although compiler optimisations make redudant.you can modify listing of elements in each area.
Comments
Post a Comment