aoc_omni/c/2024/18/ram_run.c

109 lines
2.5 KiB
C
Raw Normal View History

2024-12-25 06:06:19 -05:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "../../lib/aoc.h"
#define DIMENSION 71
#define QUEUE_LENGTH 200
typedef struct Node {
int x;
int y;
char c;
int cost;
} Node;
typedef struct Grid {
Node grid[DIMENSION][DIMENSION];
} Grid;
2024-12-25 06:15:52 -05:00
void grid_dijkstra(Grid *g) {
2024-12-25 06:06:19 -05:00
Node* queue[QUEUE_LENGTH];
2024-12-25 06:15:52 -05:00
queue[0] = &(g->grid[0][0]);
2024-12-25 06:06:19 -05:00
int queue_start = 0;
int queue_end = 1;
2024-12-25 06:15:52 -05:00
g->grid[0][0].c = '*';
g->grid[0][0].cost = 0;
2024-12-25 06:06:19 -05:00
while (queue_start != queue_end) {
// get first element of queue
Node* n = queue[queue_start++];
queue_start %= QUEUE_LENGTH;
n->c = ' ';
// add its neighbors to the queue
2024-12-25 06:15:52 -05:00
if (n->x - 1 >= 0 && g->grid[n->x - 1][n->y].c == '.') {
g->grid[n->x - 1][n->y].c = '*';
g->grid[n->x - 1][n->y].cost = n->cost + 1;
queue[queue_end++] = &(g->grid[n->x - 1][n->y]);
2024-12-25 06:06:19 -05:00
queue_end %= 200;
}
2024-12-25 06:15:52 -05:00
if (n->y - 1 >= 0 && g->grid[n->x][n->y - 1].c == '.') {
g->grid[n->x][n->y - 1].c = '*';
g->grid[n->x][n->y - 1].cost = n->cost + 1;
queue[queue_end++] = &(g->grid[n->x][n->y - 1]);
2024-12-25 06:06:19 -05:00
queue_end %= 200;
}
2024-12-25 06:15:52 -05:00
if (n->x + 1 < DIMENSION && g->grid[n->x + 1][n->y].c == '.') {
g->grid[n->x + 1][n->y].c = '*';
g->grid[n->x + 1][n->y].cost = n->cost + 1;
queue[queue_end++] = &(g->grid[n->x + 1][n->y]);
2024-12-25 06:06:19 -05:00
queue_end %= 200;
}
2024-12-25 06:15:52 -05:00
if (n->y + 1 < DIMENSION && g->grid[n->x][n->y + 1].c == '.') {
g->grid[n->x][n->y + 1].c = '*';
g->grid[n->x][n->y + 1].cost = n->cost + 1;
queue[queue_end++] = &(g->grid[n->x][n->y + 1]);
2024-12-25 06:06:19 -05:00
queue_end %= 200;
}
}
2024-12-25 06:15:52 -05:00
}
int main() {
char *line;
Grid g;
2024-12-25 06:06:19 -05:00
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j < DIMENSION; j++) {
2024-12-25 06:15:52 -05:00
g.grid[i][j].x = i;
g.grid[i][j].y = j;
g.grid[i][j].c = '.';
g.grid[i][j].cost = -1;
2024-12-25 06:06:19 -05:00
}
}
2024-12-25 06:15:52 -05:00
int x, y;
//while ((line = aoc_read_line()) != NULL) {
for (int i = 0; i < 1024; i++) {
line = aoc_read_line();
sscanf(line, "%d,%d", &x, &y);
g.grid[x][y].c = '#';
}
Grid original_grid;
memcpy(&original_grid, &g, sizeof(Grid));
grid_dijkstra(&g);
printf("Part 1: %d\n", g.grid[DIMENSION - 1][DIMENSION - 1].cost);
while ((line = aoc_read_line()) != NULL) {
sscanf(line, "%d,%d", &x, &y);
original_grid.grid[x][y].c = '#';
memcpy(&g, &original_grid, sizeof(Grid));
grid_dijkstra(&g);
if (g.grid[DIMENSION - 1][DIMENSION - 1].cost == -1) break;
}
printf("Part 2: %d,%d\n", x, y);
2024-12-25 06:06:19 -05:00
aoc_free();
exit(0);
}