QUOTE: Let your heart guide you always.

aoc

Advent of Code challenges

aoc_2024_10_2.c (1486B)


      1#include <string.h>
      2
      3#define NELEMS(x) (sizeof x / sizeof (x)[0])
      4
      5typedef struct {
      6  int y;
      7  int x;
      8} pos_t;
      9
     10const pos_t DIRS[4] = {
     11  { -1,  0 },
     12  {  0,  1 },
     13  {  1,  0 },
     14  {  0, -1 },
     15};
     16
     17void walk(
     18  size_t rows,
     19  size_t cols,
     20  unsigned int map[rows][cols],
     21  pos_t pos,
     22  int *count
     23) {
     24  for (size_t i = 0; i < NELEMS(DIRS); i++) {
     25    pos_t next = {  pos.y + DIRS[i].y, pos.x + DIRS[i].x };
     26    if (next.y < 0 || next.x < 0 || next.y >= (int) rows || next.x >= (int) cols) {
     27      continue;
     28    }
     29    unsigned int current = map[pos.y][pos.x];
     30    unsigned int forward = map[next.y][next.x];
     31    if (current + 1 != forward) {
     32      continue;
     33    }
     34    if (forward == 9) {
     35      (*count)++;
     36      continue;
     37    }
     38    walk(rows, cols, map, next, count);
     39  }
     40}
     41
     42long perform(char *data) {
     43  size_t len = strlen(data);
     44  size_t rows = 0;
     45  size_t cols = 0;
     46  for (size_t i = 0; i < len; i++) {
     47    if (data[i] == '\n') {
     48      if (rows == 0) {
     49        cols = i;
     50      }
     51      rows++;
     52    }
     53  }
     54  unsigned int map[rows][cols];
     55  for (size_t i = 0; i < len; i++) {
     56    if (data[i] == '\n') {
     57      continue;
     58    }
     59    int y = i / (cols + 1);
     60    int x = i % (cols + 1);
     61    map[y][x] = data[i] - '0';
     62  }
     63  int sum = 0;
     64  for (size_t y = 0; y < rows; y++) {
     65    for (size_t x = 0; x < cols; x++) {
     66      if (map[y][x] == 0) {
     67        pos_t pos = { y, x };
     68        int count = 0;
     69        walk(rows, cols, map, pos, &count);
     70        sum += count;
     71      }
     72    }
     73  }
     74  return sum;
     75}