Advertisement
aaaaaa123456789

Find area size (0 = walls)

Oct 31st, 2015
113
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdlib.h>
  2. #include <string.h>
  3.  
  4. unsigned area_size(unsigned char **, unsigned, unsigned, unsigned, unsigned);
  5. unsigned char ** copy_area(unsigned char **, unsigned, unsigned);
  6. void destroy_area(unsigned char **);
  7.  
  8. unsigned area_size (unsigned char ** area, unsigned width, unsigned height, unsigned x, unsigned y) {
  9.   if ((!area) || (x >= width) || (y >= height) || (!area[x][y])) return 0;
  10.   unsigned char ** copy = copy_area(area, width, height);
  11.   unsigned prevcount = 0, count = 1;
  12.   copy[x][y] = 2;
  13.   unsigned scan_area, scan_x, scan_y, neighbour_count;
  14.   for (scan_area = 1; prevcount != count; scan_area ++) {
  15.     prevcount = count;
  16.     for (scan_x = (x < scan_area) ? 0 : (x - scan_area); (scan_x < width) && (scan_x <= (x + scan_area)); scan_x ++)
  17.       for (scan_y = (y < scan_area) ? 0 : (y - scan_area); (scan_y < height) && (scan_y <= (y + scan_area)); scan_y ++) {
  18.         if (!copy[scan_x][scan_y]) continue;
  19.         if (
  20.           (scan_x && (copy[scan_x - 1][scan_y] == 2)) ||
  21.           (scan_y && (copy[scan_x][scan_y - 1] == 2)) ||
  22.           (copy[scan_x + 1][scan_y] == 2) ||
  23.           (copy[scan_x][scan_y + 1] == 2)
  24.         ) {
  25.           if (copy[scan_x][scan_y] == 1) count ++;
  26.           copy[scan_x][scan_y] = 2;
  27.         }
  28.       }
  29.   }
  30.   destroy_area(copy);
  31.   return count;
  32. }
  33.  
  34. unsigned char ** copy_area (unsigned char ** area, unsigned width, unsigned height) {
  35.   // this creates a copy of the area, and adds a surrounding border with 0s to the right and bottom to make coding easier
  36.   unsigned char ** result = calloc(sizeof(char *), width + 2);
  37.   unsigned x;
  38.   for (x = 0; x < width; x ++) {
  39.     memcpy(result[x] = malloc(height + 1), area[x], height);
  40.     result[x][height] = 0;
  41.   }
  42.   memset(result[width] = malloc(height + 1), 0, height + 1);
  43.   return result;
  44. }
  45.  
  46. void destroy_area (unsigned char ** area) {
  47.   // this destroys the copy of the area created previously
  48.   unsigned x;
  49.   for (x = 0; area[x]; x ++) free(area[x]);
  50.   free(area);
  51. }
Advertisement
RAW Paste Data Copied
Advertisement