#include #include #define MAX_DIMENSION 128 int get_trails(char**, int, int, int, int, int**); int main() { char c; char **map = calloc(MAX_DIMENSION, sizeof(map[0])); int rows = 0, i = 0, columns; map[rows] = calloc(MAX_DIMENSION, sizeof(map[0][0])); while ((c = getchar()) != EOF) { map[rows][i] = c; i++; if (c != '\n') { continue; } columns = i - 1; rows++; i = 0; map[rows] = calloc(MAX_DIMENSION, sizeof(map[0][0])); } int **reachable = calloc(rows, sizeof(reachable[0])); for (i = 0; i < rows; i++) { reachable[i] = calloc(columns, sizeof(reachable[0][0])); } int score = 0; int rating = 0; // For each '0' for (i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (map[i][j] != '0') { continue; } rating += get_trails(map, rows, columns, i, j, reachable); // Count reachable for (int k = 0; k < rows; k++) { for (int l = 0; l < columns; l++) { score += reachable[k][l]; reachable[k][l] = 0; } } } } for (i = 0; i < rows; i++) { free(reachable[i]); } free(reachable); for (i = 0; i < rows + 1; i++) { free(map[i]); } free(map); printf("%i\n", score); printf("%i\n", rating); } int get_trails(char** map, int rows, int columns, int row, int column, int** reachable) { if (map[row][column] == '9') { reachable[row][column] = 1; return 1; } int x, y; char next = map[row][column] + 1; int trails = 0; // up x = row - 1; y = column; if (x >= 0 && map[x][y] == next) { trails += get_trails(map, rows, columns, x, y, reachable); } // down x = row + 1; y = column; if (x < rows && map[x][y] == next) { trails += get_trails(map, rows, columns, x, y, reachable); } // left x = row; y = column + 1; if (y < columns && map[x][y] == next) { trails += get_trails(map, rows, columns, x, y, reachable); } // right x = row; y = column - 1; if (y >= 0 && map[x][y] == next) { trails += get_trails(map, rows, columns, x, y, reachable); } return trails; }