aboutsummaryrefslogtreecommitdiff
path: root/04/part1.c
blob: 9ebdb462a6d320f69b0458db416d47c1c02a7c56 (plain)
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
#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];
}


bool is_paper(StringVector *map, int x, int y) {
    return map_read(map, x, y) == '@';
}

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;
}

void free_map(StringVector *map) {
    for (int i = 0; i < StringVector_len(map); i++) {
        free((void*)*StringVector_ref(map, i));
    }
    StringVector_free(map);
}

int main() {
    StringVector map = readmap();
    int height = StringVector_len(&map);
    int width = strlen(*StringVector_ref(&map, 0));
    int res = 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) {
                res++;
            }
        }
    }
    printf("%d\n", res);

    free_map(&map);
    return 0;
}