common.c (1721B)
1 #include "common.h" 2 3 uint8_t **parse(size_t *h, size_t *w, size_t *pos, char **lines, 4 size_t nlines) { 5 size_t i, j; 6 7 *h = nlines; 8 *w = strlen(lines[0]) - 1; 9 10 uint8_t **grid = malloc(*h * sizeof(*grid)); 11 for (i = 0; i < *h; i++) 12 grid[i] = malloc(*w * sizeof(**grid)); 13 14 for (i = 0; i < nlines; i++) { 15 for (j = 0; j < *w; j++) { 16 if (lines[i][j] == 'S') { 17 pos[0] = i; 18 pos[1] = j; 19 lines[i][j] = 'a'; 20 } else if (lines[i][j] == 'E') { 21 pos[2] = i; 22 pos[3] = j; 23 lines[i][j] = 'z'; 24 } 25 grid[i][j] = (uint8_t)(lines[i][j] - 'a'); 26 } 27 } 28 29 return grid; 30 } 31 32 void calculate_steps(uint64_t *stepsto, size_t ex, size_t ey, size_t h, 33 size_t w, uint8_t **grid) { 34 size_t i; 35 SIMPLEQ_HEAD(listhead, entry) head = SIMPLEQ_HEAD_INITIALIZER(head); 36 37 struct entry *pos = malloc(sizeof(*pos)); 38 pos->x = ex; 39 pos->y = ey; 40 SIMPLEQ_INSERT_TAIL(&head, pos, entries); 41 42 while (!SIMPLEQ_EMPTY(&head)) { 43 pos = SIMPLEQ_FIRST(&head); 44 size_t x = pos->x, y = pos->y; 45 SIMPLEQ_REMOVE_HEAD(&head, entries); 46 int delta[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 47 for (i = 0; i < 4; i++) { 48 int cx = (int)x + delta[i][0]; 49 int cy = (int)y + delta[i][1]; 50 if (cx < 0 || cy < 0 || cx >= h || cy >= w) { 51 continue; 52 } 53 if (grid[cx][cy] + 1 >= grid[x][y]) { 54 if (stepsto[x * w + y] + 1 < stepsto[cx * w + cy]) { 55 stepsto[cx * w + cy] = stepsto[x * w + y] + 1; 56 struct entry *npos = malloc(sizeof(*npos)); 57 npos->x = cx; 58 npos->y = cy; 59 SIMPLEQ_INSERT_TAIL(&head, npos, entries); 60 } 61 } 62 } 63 free(pos); 64 } 65 }