uppga.c (2132B)
1 #include "common.h" 2 3 static inline int is_expandable_row(size_t i, char **lines, size_t ncols) { 4 size_t j; 5 for (j = 0; j < ncols; j++) { 6 if (lines[i][j] != '.') 7 return 0; 8 } 9 return 1; 10 } 11 12 static inline int is_expandable_col(size_t i, char **lines, size_t nrows) { 13 size_t j; 14 for (j = 0; j < nrows; j++) { 15 if (lines[j][i] != '.') 16 return 0; 17 } 18 return 1; 19 } 20 21 static inline int isin(size_t i, size_t *lst, size_t nlst) { 22 size_t j; 23 for (j = 0; j < nlst; j++) { 24 if (lst[j] == i) 25 return 1; 26 } 27 28 return 0; 29 } 30 31 static inline uint64_t count_betw(size_t ca, size_t cb, size_t *lst, 32 size_t nlst) { 33 size_t mi = ca > cb ? cb : ca; 34 size_t ma = ca > cb ? ca : cb; 35 36 uint64_t count = 0; 37 size_t i; 38 for (i = mi; i < ma; i++) { 39 if (isin(i, lst, nlst)) { 40 count += 2; 41 } else { 42 count++; 43 } 44 } 45 46 return count; 47 } 48 49 int main(int argc, char **argv) { 50 char **lines; 51 size_t i, j; 52 size_t nrows = readlines(&lines, "input"); 53 size_t ncols = strlen(lines[0]) - 1; 54 55 size_t expand_cols[2 * ncols]; 56 size_t expand_rows[2 * nrows]; 57 size_t nexpand_cols = 0; 58 size_t nexpand_rows = 0; 59 60 for (i = 0; i < nrows; i++) { 61 if (is_expandable_row(i, lines, ncols)) { 62 expand_rows[nexpand_rows] = i; 63 nexpand_rows++; 64 } 65 } 66 67 for (i = 0; i < ncols; i++) { 68 if (is_expandable_col(i, lines, nrows)) { 69 expand_cols[nexpand_cols] = i; 70 nexpand_cols++; 71 } 72 } 73 74 size_t galaxies[4 * ncols * nrows][2]; 75 size_t ngalaxies = 0; 76 for (i = 0; i < nrows; i++) { 77 for (j = 0; j < ncols; j++) { 78 if (lines[i][j] == '#') { 79 galaxies[ngalaxies][0] = i; 80 galaxies[ngalaxies][1] = j; 81 ngalaxies++; 82 } 83 } 84 } 85 86 uint64_t summarum = 0; 87 for (i = 0; i < ngalaxies - 1; i++) { 88 for (j = i + 1; j < ngalaxies; j++) { 89 uint64_t rowc = 90 count_betw(galaxies[i][0], galaxies[j][0], expand_rows, nexpand_rows); 91 uint64_t colc = 92 count_betw(galaxies[i][1], galaxies[j][1], expand_cols, nexpand_cols); 93 summarum += rowc + colc; 94 } 95 } 96 97 printf("%llu\n", summarum); 98 }