diff options
Diffstat (limited to '8.c')
-rw-r--r-- | 8.c | 73 |
1 files changed, 71 insertions, 2 deletions
@@ -3,6 +3,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> // Check if a tree is newly seen, by being taller than max or not @@ -65,12 +66,65 @@ forest_seen(unsigned char * forest, int rows, int cols) } +// Get the maximum scenic score for a tree int -main() +forest_maxscore(unsigned char * forest, int rows, int cols) { + int i, j, max = 0; + + for (i = 1; i < rows - 1; ++i) { + for (j = 1; j < cols - 2; ++j) { + int dist; + int score = 1; + int height = forest[i * cols + j]; + + for (dist = 1; j - dist > 0; ++dist) + if (forest[i * cols + j - dist] >= height) + break; + score *= dist; + + for (dist = 1; j + dist < cols - 2; ++dist) + if (forest[i * cols + j + dist] >= height) + break; + score *= dist; + + for (dist = 1; i - dist > 0; ++dist) + if (forest[(i - dist) * cols + j] >= height) + break; + score *= dist; + + for (dist = 1; i + dist < rows - 1; ++dist) + if (forest[(i + dist) * cols + j] >= height) + break; + score *= dist; + + if (score > max) + max = score; + } + } + + return max; +} + + +int +main(int argc, char ** argv) +{ + int i, part = 1; int cols = 0, rows = 0; char * forest; + while ((i = getopt(argc, argv, "p:")) != -1) { + switch (i) { + case 'p': + part = atoi(optarg); + break; + + default: + return -1; + } + } + // Read first line forest = malloc(BUFSIZ); if (!fgets(forest, BUFSIZ, stdin)) { @@ -115,7 +169,22 @@ main() ++rows; } - printf("Trees seen: %d\n", forest_seen((unsigned char *) forest, rows, cols)); + switch (part) { + case 1: + printf("Trees seen: %d\n", + forest_seen((unsigned char *) forest, rows, cols)); + break; + + case 2: + printf("Best visibility: %d\n", + forest_maxscore((unsigned char *) forest, rows, cols)); + break; + + default: + fprintf(stderr, "Unexpected part %d\n", part); + free(forest); + return -1; + } free(forest); |