#include #include #include #if 0 #define KNOTS 2 #else #define KNOTS 10 #endif #if 0 #define FILENAME "sample.txt" #else #define FILENAME "input.txt" #endif #define SIDE 1000 #define OFFSET (SIDE/2) typedef enum { NONE = 0, NORTH = 1, SOUTH = -1, EAST = 1, WEST = -1 } direction; int board[SIDE][SIDE] = {0}; int rope[KNOTS][2] = {0}; direction rope_dir[KNOTS][2] = {0}; void move(int k) { rope[k][0] += rope_dir[k][0]; rope[k][1] += rope_dir[k][1]; } void parse_dir(char d) { rope_dir[0][0] = NONE; rope_dir[0][1] = NONE; switch(d) { case 'U': rope_dir[0][1] = NORTH; return; case 'D': rope_dir[0][1] = SOUTH; return; case 'R': rope_dir[0][0] = EAST; return; case 'L': rope_dir[0][0] = WEST; return; } } void parse() { FILE *fp = fopen(FILENAME, "r"); if(!fp) { fprintf(stderr, "ERROR: Could not open file: %s\n", FILENAME); exit(1); } char line[256]; while(fgets(line, sizeof(line), fp)) { parse_dir(strtok(line, " ")[0]); int n = atoi(strtok(NULL, " ")); for(int i = 0; i < n; i++) { move(0); for(int j = 1; j < KNOTS; j++) { int hor = rope[j-1][0] - rope[j][0]; if(hor > 0) rope_dir[j][0] = EAST; else if(hor < 0) rope_dir[j][0] = WEST; else rope_dir[j][0] = NONE; int vert = rope[j-1][1] - rope[j][1]; if(vert > 0) rope_dir[j][1] = NORTH; else if(vert < 0) rope_dir[j][1] = SOUTH; else rope_dir[j][1] = NONE; if(abs(vert) > 1 || abs(hor) > 1) move(j); } board[rope[KNOTS-1][0] + OFFSET][rope[KNOTS-1][1] + OFFSET]++; } } fclose(fp); } int sum() { int sum = 0; for(int i = 0; i < SIDE; i++) for(int j = 0; j < SIDE; j++) if(board[j][i] > 0) sum++; return sum; } int main(void) { parse(); printf("%d\n", sum()); return 0; }