1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Grid {
int h, w;
char c[128][128];
};
static char at(const struct Grid *grid, int y, int x) {
if (x < 0 || y < 0 || x >= grid->w || y >= grid->h) return '.';
return grid->c[y][x];
}
static int adj(const struct Grid *grid, int y, int x) {
return (
(at(grid, y - 1, x - 1) == '#') +
(at(grid, y - 1, x + 0) == '#') +
(at(grid, y - 1, x + 1) == '#') +
(at(grid, y + 0, x - 1) == '#') +
(at(grid, y + 0, x + 1) == '#') +
(at(grid, y + 1, x - 1) == '#') +
(at(grid, y + 1, x + 0) == '#') +
(at(grid, y + 1, x + 1) == '#')
);
}
static struct Grid gen1(const struct Grid *prev) {
struct Grid next = { .h = prev->h, .w = prev->w };
for (int y = 0; y < next.h; ++y) {
for (int x = 0; x < next.w; ++x) {
if (prev->c[y][x] == 'L' && !adj(prev, y, x)) {
next.c[y][x] = '#';
} else if (prev->c[y][x] == '#' && adj(prev, y, x) >= 4) {
next.c[y][x] = 'L';
} else {
next.c[y][x] = prev->c[y][x];
}
}
}
return next;
}
static char ray(const struct Grid *grid, int y, int x, int dy, int dx) {
y += dy;
x += dx;
while (y >= 0 && y < grid->h && x >= 0 && x < grid->w) {
if (grid->c[y][x] != '.') return grid->c[y][x];
y += dy;
x += dx;
}
return '.';
}
static int see(const struct Grid *grid, int y, int x) {
return (
(ray(grid, y, x, -1, -1) == '#') +
(ray(grid, y, x, -1, +0) == '#') +
(ray(grid, y, x, -1, +1) == '#') +
(ray(grid, y, x, +0, -1) == '#') +
(ray(grid, y, x, +0, +1) == '#') +
(ray(grid, y, x, +1, -1) == '#') +
(ray(grid, y, x, +1, +0) == '#') +
(ray(grid, y, x, +1, +1) == '#')
);
}
static struct Grid gen2(const struct Grid *prev) {
struct Grid next = { .h = prev->h, .w = prev->w };
for (int y = 0; y < next.h; ++y) {
for (int x = 0; x < next.w; ++x) {
if (prev->c[y][x] == 'L' && !see(prev, y, x)) {
next.c[y][x] = '#';
} else if (prev->c[y][x] == '#' && see(prev, y, x) >= 5) {
next.c[y][x] = 'L';
} else {
next.c[y][x] = prev->c[y][x];
}
}
}
return next;
}
int main(void) {
struct Grid init = {0};
while (EOF != scanf("%s\n", init.c[init.h])) {
init.h++;
}
init.w = strlen(init.c[0]);
struct Grid prev = init;
for (;;) {
struct Grid next = gen1(&prev);
if (!memcmp(&next, &prev, sizeof(next))) break;
prev = next;
}
int occ = 0;
for (int y = 0; y < prev.h; ++y) {
for (int x = 0; x < prev.w; ++x) {
occ += prev.c[y][x] == '#';
}
}
printf("%d\n", occ);
prev = init;
for (;;) {
struct Grid next = gen2(&prev);
if (!memcmp(&next, &prev, sizeof(next))) break;
prev = next;
}
occ = 0;
for (int y = 0; y < prev.h; ++y) {
for (int x = 0; x < prev.w; ++x) {
occ += prev.c[y][x] == '#';
}
}
printf("%d\n", occ);
}
|