diff options
| author | Mistivia <i@mistivia.com> | 2025-12-21 19:03:29 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2025-12-21 19:03:29 +0800 |
| commit | f6a4f79dacab0218d5ffd4ec04244c8e6b36a8a5 (patch) | |
| tree | 6d3e1174d173638937674b363235d8d96809d534 /04/part2.c | |
| parent | 91c777fc315233341b19677f816048ab63a8a667 (diff) | |
day 4 part 2
Diffstat (limited to '04/part2.c')
| -rw-r--r-- | 04/part2.c | 119 |
1 files changed, 119 insertions, 0 deletions
@@ -0,0 +1,119 @@ +#include <algds/str.h> +#include <algds/vec.h> + +StringVector readmap() { + StringVector map; + StringVector_init(&map); + while (1) { + char *l = fgetline(stdin); + if (!l) { + return map; + } + char *nl = str_strip(l); + free(l); + l = nl; + if (strlen(l) == 0) { + return map; + } + StringVector_push_back(&map, l); + } + return map; +} + +char map_read(StringVector *map, int x, int y) { + int height = StringVector_len(map); + if (height == 0) { + return '\0'; + } + int width = strlen(*StringVector_ref(map, 0)); + if (x >= width || x < 0) { + return '\0'; + } + if (y >= height || y < 0) { + return '\0'; + } + return (*StringVector_ref(map, y))[x]; +} + +void map_set(StringVector *map, int x, int y, char c) { + int height = StringVector_len(map); + if (height == 0) { + return; + } + int width = strlen(*StringVector_ref(map, 0)); + if (x >= width || x < 0) { + return; + } + if (y >= height || y < 0) { + return; + } + ((char*)*StringVector_ref(map, y))[x] = c; +} + + +bool is_paper(StringVector *map, int x, int y) { + char c = map_read(map, x, y); + return c == '@'; +} + +int count_adjacent(StringVector *map, int x, int y) { + int count = 0; + if (is_paper(map, x - 1, y - 1)) { + count++; + } + if (is_paper(map, x - 1, y)) { + count++; + } + if (is_paper(map, x, y - 1)) { + count++; + } + if (is_paper(map, x + 1, y + 1)) { + count++; + } + if (is_paper(map, x + 1, y)) { + count++; + } + if (is_paper(map, x, y + 1)) { + count++; + } + if (is_paper(map, x + 1, y - 1)) { + count++; + } + if (is_paper(map, x - 1, y + 1)) { + count++; + } + return count; +} + +int iter(StringVector *map, int height, int width) { + int forked = 0; + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + if (map_read(map, x, y) != '@') { + continue; + } + if (count_adjacent(map, x, y) < 4) { + map_set(map, x, y, 'x'); + forked++; + } + } + } + return forked; +} + +int main() { + StringVector map = readmap(); + int height = StringVector_len(&map); + int width = strlen(*StringVector_ref(&map, 0)); + int res = 0; + while (1) { + int n = iter(&map, height, width); + if (n > 0) { + res += n; + } else { + break; + } + } + printf("%d\n", res); + return 0; +}
\ No newline at end of file |
