#include #include #include #include #if 0 #define PART part1 #else #define PART part2 #endif #if 0 #define FILENAME "sample.txt" #define WIDTH 600 #define HEIGHT 20 #else #define FILENAME "input.txt" #define WIDTH 2000 #define HEIGHT 500 #endif #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) int map[WIDTH][HEIGHT] = {0}; int max_y = INT_MIN; int sands = 0; int sim_sand() { int sand_x = 500; int sand_y = 0; while(1) { if(sand_y >= max_y) return -1; if(map[sand_x][sand_y + 1] != 1) { sand_y++; } else if(map[sand_x - 1][sand_y + 1] != 1) { sand_x--; sand_y++; } else if(map[sand_x + 1][sand_y + 1] != 1) { sand_x++; sand_y++; } else break; continue; } map[sand_x][sand_y] = 1; return 0; } void part1() { while(sim_sand() == 0) sands++; } void draw_line(int x1, int y1, int x2, int y2); void part2() { draw_line(0, max_y + 2, WIDTH-1, max_y + 2); max_y = INT_MAX; while(map[500][0] != 1) { sim_sand(); sands++; } } void draw_line(int x1, int y1, int x2, int y2) { if(x1 != x2 && y1 == y2) for(int x = MIN(x1, x2); x <= MAX(x1, x2); x++) map[x][y1] = 1; else if(y1 != y2 && x1 == x2) for(int y = MIN(y1, y2); y <= MAX(y1, y2); y++) map[x1][y] = 1; } void parse() { FILE *fp = fopen(FILENAME, "r"); if(!fp) { fprintf(stderr, "ERROR: Could not open file %s\n", FILENAME); exit(1); } char line[5000]; while(fgets(line, sizeof(line), fp)) { int x1 = -1; int y1 = -1; int x2 = -1; int y2 = -1; char *sprt1; char *tok = strtok_r(line, " -> ", &sprt1); while(tok != NULL) { char *sprt2; x2 = atoi(strtok_r(tok, ",", &sprt2)); y2 = atoi(strtok_r(NULL, ",", &sprt2)); max_y = MAX(max_y, y2); if(x1 != -1 && y1 != -1) draw_line(x1, y1, x2, y2); x1 = x2; y1 = y2; tok = strtok_r(NULL, " -> ", &sprt1); } } fclose(fp); } int main(void) { parse(); PART(); printf("%d\n", sands); return 0; }