day04.c (1288B)
1 #include <stdio.h> 2 #include <string.h> 3 #include "cputime.h" 4 5 // +1 on all sides 6 #define W 141 7 #define H 141 8 9 #define LEN(x) (sizeof((x))/sizeof(*(x))) 10 11 typedef char Map[H][W]; 12 typedef struct { 13 int x, y; 14 } Point; 15 16 int count_adj(Map map, int x, int y) { 17 int cnt = 0; 18 Point points[] = { 19 {x-1,y+1}, {x,y+1}, {x+1,y+1}, 20 {x-1,y }, {x+1,y }, 21 {x-1,y-1}, {x,y-1}, {x+1,y-1} 22 }; 23 for (size_t p=0;p<LEN(points);++p) { 24 if (map[points[p].y][points[p].x]=='@') cnt++; 25 } 26 return cnt; 27 } 28 29 int clean(Map map) { 30 Map map1; 31 memcpy(map1, map, sizeof(Map)); 32 int rem = 0; 33 for (int y=1;y<H-1;++y) { 34 for (int x=1;x<W-1;++x) { 35 if (map1[y][x]=='@'&&count_adj(map1, x, y)<4) { 36 map[y][x]='.'; 37 rem++; 38 } 39 } 40 } 41 42 return rem; 43 } 44 45 int main(void) { 46 Map map = {0}; 47 int x = 1; 48 int y = 1; 49 for (int c=getchar();c!=EOF;c=getchar()) { 50 if (c!='\n') map[y][x++] = c; 51 else { 52 y++; 53 x=1; 54 } 55 } 56 57 int p1 = 0; 58 int p2 = 0; 59 while (1) { 60 int rem = clean(map); 61 p2 += rem; 62 if (p1==0) p1 = rem; 63 if (rem==0) break; 64 } 65 printf("p1: %d\np2: %d\n", p1, p2); 66 return 0; 67 }