aocc23

Advent of Code 2023
git clone git://www.tkruger.se/aocc23.git
Log | Files | Refs | README

common.c (1348B)


      1 #include "common.h"
      2 
      3 static inline size_t idx(size_t row, size_t col, size_t ncols) {
      4   return row * ncols + col;
      5 }
      6 
      7 static inline int walkable(char **lines, size_t r, size_t c) {
      8   return lines[r][c] == '.' || lines[r][c] == 'S';
      9 }
     10 
     11 static inline void edge_adder(graph_t *g, char **lines, size_t nlines,
     12                               size_t ncols, size_t row, size_t col) {
     13   // north
     14   if (row > 0 && walkable(lines, row - 1, col)) {
     15     graph_add_edge(g, idx(row, col, ncols), idx(row - 1, col, ncols));
     16   }
     17 
     18   // east
     19   if (col < ncols - 1 && walkable(lines, row, col + 1)) {
     20     graph_add_edge(g, idx(row, col, ncols), idx(row, col + 1, ncols));
     21   }
     22 
     23   // south
     24   if (row < nlines - 1 && walkable(lines, row + 1, col)) {
     25     graph_add_edge(g, idx(row, col, ncols), idx(row + 1, col, ncols));
     26   }
     27 
     28   // west
     29   if (col > 0 && walkable(lines, row, col - 1)) {
     30     graph_add_edge(g, idx(row, col, ncols), idx(row, col - 1, ncols));
     31   }
     32 }
     33 
     34 void read_grid(graph_t *g, size_t *start, char **lines, size_t nlines) {
     35   size_t i, j;
     36   size_t ncols = strlen(lines[0]) - 1;
     37 
     38   graph_init(g, nlines * ncols);
     39   for (i = 0; i < nlines; i++) {
     40     for (j = 0; j < ncols; j++) {
     41       if (lines[i][j] == '.' || lines[i][j] == 'S')
     42         edge_adder(g, lines, nlines, ncols, i, j);
     43       if (lines[i][j] == 'S')
     44         *start = idx(i, j, ncols);
     45     }
     46   }
     47 }