Day20 Day21 C WIP
This commit is contained in:
102
day21/c/day21.c
Normal file
102
day21/c/day21.c
Normal file
@@ -0,0 +1,102 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define LINE_MAX_LENGTH 256
|
||||
|
||||
typedef enum tile_type {
|
||||
GARDEN_PLOT,
|
||||
ROCK,
|
||||
WALKED,
|
||||
} tile_type_t;
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 2) {
|
||||
fprintf(stderr, "Please specify the step number\n");
|
||||
return 1;
|
||||
}
|
||||
int step_number = 0;
|
||||
sscanf(argv[1], "%i", &step_number);
|
||||
char *p, *buf, c;
|
||||
|
||||
tile_type_t map[LINE_MAX_LENGTH][LINE_MAX_LENGTH];
|
||||
int x = 0, y = 0;
|
||||
|
||||
buf = (char *)malloc(LINE_MAX_LENGTH);
|
||||
memset(buf, 0, LINE_MAX_LENGTH);
|
||||
p = buf;
|
||||
|
||||
int start[2];
|
||||
|
||||
while ((c = getchar()) != EOF) {
|
||||
*p++ = c;
|
||||
if (c == '\n') {
|
||||
p = buf;
|
||||
x = 0;
|
||||
while (*p != '\n') {
|
||||
switch (*p) {
|
||||
case '.':
|
||||
map[x][y] = GARDEN_PLOT;
|
||||
break;
|
||||
case '#':
|
||||
map[x][y] = ROCK;
|
||||
break;
|
||||
case 'S':
|
||||
map[x][y] = GARDEN_PLOT;
|
||||
start[0] = x;
|
||||
start[1] = y;
|
||||
break;
|
||||
}
|
||||
x++;
|
||||
p++;
|
||||
}
|
||||
y++;
|
||||
memset(buf, 0, LINE_MAX_LENGTH);
|
||||
p = buf;
|
||||
}
|
||||
}
|
||||
|
||||
tile_type_t walked_curr[LINE_MAX_LENGTH][LINE_MAX_LENGTH], walked_next[LINE_MAX_LENGTH][LINE_MAX_LENGTH];
|
||||
memcpy(walked_curr, map, sizeof(map));
|
||||
walked_curr[start[0]][start[1]] = WALKED;
|
||||
|
||||
for (int i = 0; i < step_number; i++) {
|
||||
memcpy(walked_next, map, sizeof(map));
|
||||
for (int j = 0; j < y; j++) {
|
||||
for (int k = 0; k < x; k++) {
|
||||
if (walked_curr[k][j] == WALKED) {
|
||||
// UP
|
||||
if (j > 0 && walked_next[k][j-1] == GARDEN_PLOT) {
|
||||
walked_next[k][j-1] = WALKED;
|
||||
}
|
||||
// LEFT
|
||||
if (k > 0 && walked_next[k-1][j] == GARDEN_PLOT) {
|
||||
walked_next[k-1][j] = WALKED;
|
||||
}
|
||||
// DOWN
|
||||
if (j < y - 1 && walked_next[k][j+1] == GARDEN_PLOT) {
|
||||
walked_next[k][j+1] = WALKED;
|
||||
}
|
||||
// RIGHT
|
||||
if (k < x - 1 && walked_next[k+1][j] == GARDEN_PLOT) {
|
||||
walked_next[k+1][j] = WALKED;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
memcpy(walked_curr, walked_next, sizeof(map));
|
||||
}
|
||||
|
||||
int part1 = 0;
|
||||
|
||||
for (int i = 0; i < y; i++) {
|
||||
for (int j = 0; j < x; j++) {
|
||||
if (walked_curr[j][i] == WALKED) {
|
||||
part1++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printf("%i\n", part1);
|
||||
free(buf);
|
||||
}
|
||||
Reference in New Issue
Block a user