1.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <htable.h>
  4. #include <crc32.h>
  5. typedef struct {
  6. int x;
  7. int y;
  8. } Point;
  9. uint32_t point_hash(void *point) {
  10. return crc32(0, point, sizeof(Point));
  11. }
  12. bool point_eq(void *x, void *y) {
  13. Point *a = x, *b = y;
  14. return (a->x == b->x) && (a->y == b->y);
  15. }
  16. typedef struct {
  17. Point head;
  18. Point tail;
  19. } State;
  20. bool is_adjacent(Point p1, Point p2) {
  21. if (abs(p1.x - p2.x) <= 1 && abs(p2.y - p1.y) <= 1) {
  22. return true;
  23. }
  24. return false;
  25. }
  26. void run_impl(State *s, HTable *record, int dx, int dy) {
  27. Point new = {s->head.x + dx, s->head.y + dy};
  28. if (!is_adjacent(s->tail, new)) {
  29. s->tail = s->head;
  30. htable_insert(record , &(s->tail));
  31. }
  32. s->head = new;
  33. }
  34. void run(State *s, HTable *record, char direction, int step) {
  35. int dx, dy;
  36. switch (direction) {
  37. case 'U':
  38. dx = 0; dy = 1;
  39. break;
  40. case 'D':
  41. dx = 0; dy = -1;
  42. break;
  43. case 'L':
  44. dx = -1; dy = 0;
  45. break;
  46. case 'R':
  47. dx = 1; dy = 0;
  48. break;
  49. default:
  50. return;
  51. }
  52. for (int i = 0; i < step; i++) {
  53. run_impl(s, record, dx, dy);
  54. }
  55. }
  56. int count_htable(HTable *ht) {
  57. int count = 0;
  58. for (void *iter = htable_begin(ht);
  59. iter != NULL;
  60. iter = htable_next(ht, iter)) {
  61. count++;
  62. }
  63. return count;
  64. }
  65. int main() {
  66. FILE *fp = fopen("input", "r");
  67. State state;
  68. state.head = (Point){0, 0};
  69. state.tail = (Point){0, 0};
  70. char direction;
  71. int step;
  72. HTable record;
  73. htable_init(&record, sizeof(Point), -1, point_hash, point_eq);
  74. while (fscanf(fp, "%c %d", &direction, &step) != EOF) {
  75. run(&state, &record, direction, step);
  76. }
  77. int count = count_htable(&record);
  78. printf("%d\n", count);
  79. return 0;
  80. }