瀏覽代碼

day 10 go)))

metya 1 年之前
父節點
當前提交
2b2ad75b2d
共有 7 個文件被更改,包括 384 次插入1 次删除
  1. 10 0
      aoc2024/README.md
  2. 1 1
      aoc2024/aocutils.py
  3. 190 0
      aoc2024/day10/README.md
  4. 133 0
      aoc2024/day10/day10.go
  5. 0 0
      aoc2024/day10/day10.py
  6. 8 0
      aoc2024/day10/example.txt
  7. 42 0
      aoc2024/day10/input.txt

+ 10 - 0
aoc2024/README.md

@@ -0,0 +1,10 @@
+# Advent of Code 2024
+
+https://adventofcode.com/2024
+
+
+The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit.
+
+As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th.
+
+Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!

+ 1 - 1
aoc2024/aocutils.py

@@ -86,7 +86,7 @@ def bench(part):
 
 
 if __name__ == "__main__":
-    day = 9
+    day = 10
     root = os.path.dirname(__file__)
     task_dir = os.path.join(root, f"day{day}")
     generate_readme(task_dir, day)

+ 190 - 0
aoc2024/day10/README.md

@@ -0,0 +1,190 @@
+--- Day 10: Hoof It ---
+-----------------------
+
+You all arrive at a [Lava Production Facility](/2023/day/15) on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat.
+
+
+The reindeer is holding a book titled "Lava Island Hiking Guide". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank [topographic map](https://en.wikipedia.org/wiki/Topographic_map) of the surrounding area (your puzzle input) and looks up at you excitedly.
+
+
+Perhaps you can help fill in the missing hiking trails?
+
+
+The topographic map indicates the *height* at each position using a scale from `0` (lowest) to `9` (highest). For example:
+
+
+
+```
+0123
+1234
+8765
+9876
+
+```
+
+Based on un-scorched scraps of the book, you determine that a good hiking trail is *as long as possible* and has an *even, gradual, uphill slope*. For all practical purposes, this means that a *hiking trail* is any path that starts at height `0`, ends at height `9`, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map).
+
+
+You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails.
+
+
+A *trailhead* is any position that starts one or more hiking trails - here, these positions will always have height `0`. Assembling more fragments of pages, you establish that a trailhead's *score* is the number of `9`-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of `1` because it can reach a single `9` (the one in the bottom left).
+
+
+This trailhead has a score of `2`:
+
+
+
+```
+...0...
+...1...
+...2...
+6543456
+7.....7
+8.....8
+9.....9
+
+```
+
+(The positions marked `.` are impassable tiles to simplify these examples; they do not appear on your actual topographic map.)
+
+
+This trailhead has a score of `4` because every `9` is reachable via a hiking trail except the one immediately to the left of the trailhead:
+
+
+
+```
+..90..9
+...1.98
+...2..7
+6543456
+765.987
+876....
+987....
+
+```
+
+This topographic map contains *two* trailheads; the trailhead at the top has a score of `1`, while the trailhead at the bottom has a score of `2`:
+
+
+
+```
+10..9..
+2...8..
+3...7..
+4567654
+...8..3
+...9..2
+.....01
+
+```
+
+Here's a larger example:
+
+
+
+```
+89010123
+78121874
+87430965
+96549874
+45678903
+32019012
+01329801
+10456732
+
+```
+
+This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of `5`, `6`, `5`, `3`, `1`, `3`, `5`, `3`, and `5`. Adding these scores together, the sum of the scores of all trailheads is `*36*`.
+
+
+The reindeer gleefully carries over a protractor and adds it to the pile. *What is the sum of the scores of all trailheads on your topographic map?*
+
+
+--- Part Two ---
+----------------
+
+The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper.
+
+
+The paper describes a second way to measure a trailhead called its *rating*. A trailhead's rating is the *number of distinct hiking trails* which begin at that trailhead. For example:
+
+
+
+```
+.....0.
+..4321.
+..5..2.
+..6543.
+..7..4.
+..8765.
+..9....
+
+```
+
+The above map has a single trailhead; its rating is `3` because there are exactly three distinct hiking trails which begin at that position:
+
+
+
+```
+.....0.   .....0.   .....0.
+..4321.   .....1.   .....1.
+..5....   .....2.   .....2.
+..6....   ..6543.   .....3.
+..7....   ..7....   .....4.
+..8....   ..8....   ..8765.
+..9....   ..9....   ..9....
+
+```
+
+Here is a map containing a single trailhead with rating `13`:
+
+
+
+```
+..90..9
+...1.98
+...2..7
+6543456
+765.987
+876....
+987....
+
+```
+
+This map contains a single trailhead with rating `227` (because there are `121` distinct hiking trails that lead to the `9` on the right edge and `106` that lead to the `9` on the bottom edge):
+
+
+
+```
+012345
+123456
+234567
+345678
+4.6789
+56789.
+
+```
+
+Here's the larger example from before:
+
+
+
+```
+89010123
+78121874
+87430965
+96549874
+45678903
+32019012
+01329801
+10456732
+
+```
+
+Considering its trailheads in reading order, they have ratings of `20`, `24`, `10`, `4`, `1`, `4`, `5`, `8`, and `5`. The sum of all trailhead ratings in this larger example topographic map is `*81*`.
+
+
+You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. *What is the sum of the ratings of all trailheads?*
+
+

+ 133 - 0
aoc2024/day10/day10.go

@@ -0,0 +1,133 @@
+package main
+
+import (
+	"bufio"
+	"flag"
+	"fmt"
+	"os"
+	"time"
+)
+
+func main() {
+	example := flag.Bool("example", false, "example or input")
+	flag.Parse()
+	filename := "input.txt"
+	if *example {
+		filename = "example.txt"
+	}
+	file, err := os.Open(filename)
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	defer file.Close()
+
+	var grid [][]int
+	scanner := bufio.NewScanner(file)
+	for scanner.Scan() {
+		line := scanner.Text()
+		row := []int{}
+		for _, c := range line {
+			row = append(row, int(c-'0'))
+		}
+		grid = append(grid, row)
+	}
+
+	if err := scanner.Err(); err != nil {
+		fmt.Println(err)
+		return
+	}
+
+	// part 1
+	start := time.Now()
+	totalScore := calculateTrailheadScores(grid, bfs)
+	end1 := time.Since(start)
+
+	// part 2
+	start = time.Now()
+	totalRating := calculateTrailheadScores(grid, countUniqueTrails)
+	end2 := time.Since(start)
+
+	fmt.Println("Sum of Trailheads:", totalScore, "with time:", end1)
+	fmt.Println("Sum of Rating:", totalRating, "with time:", end2)
+}
+
+func calculateTrailheadScores(grid [][]int, bfs func([][]int, int, int) int) int {
+	totalScore := 0
+	for y, row := range grid {
+		for x, cell := range row {
+			if cell == 0 {
+				score := bfs(grid, x, y)
+				totalScore += score
+			}
+		}
+	}
+	return totalScore
+}
+
+func countUniqueTrails(grid [][]int, startX, startY int) int {
+	height, width := len(grid), len(grid[0])
+	memo := make(map[[3]int]int)
+
+	var dfs func(x, y, prevHeight int) int
+	dfs = func(x, y, prevHeight int) int {
+		if x < 0 || x >= width || y < 0 || y >= height || grid[y][x] != prevHeight+1 {
+			return 0
+		}
+
+		if grid[y][x] == 9 {
+			return 1
+		}
+
+		state := [3]int{x, y, grid[y][x]}
+		if result, found := memo[state]; found {
+			return result
+		}
+
+		directions := [][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
+		count := 0
+		for _, d := range directions {
+			nx, ny := x+d[0], y+d[1]
+			count += dfs(nx, ny, grid[y][x])
+		}
+
+		memo[state] = count
+		return count
+	}
+
+	return dfs(startX, startY, -1) // start with -1, to head 0
+}
+
+func bfs(grid [][]int, startX, startY int) int {
+	directions := [][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
+	height, width := len(grid), len(grid[0])
+	visited := make(map[[2]int]bool)
+	queue := [][2]int{{startX, startY}}
+	visited[[2]int{startX, startY}] = true
+
+	reachableNines := 0
+
+	for len(queue) > 0 {
+		x, y := queue[0][0], queue[0][1]
+		queue = queue[1:]
+
+		for _, d := range directions {
+			nx, ny := x+d[0], y+d[1]
+
+			if nx < 0 || nx >= width || ny < 0 || ny >= height {
+				continue
+			}
+
+			if !visited[[2]int{nx, ny}] && grid[ny][nx] == grid[y][x]+1 {
+				visited[[2]int{nx, ny}] = true
+				queue = append(queue, [2]int{nx, ny})
+
+				if grid[ny][nx] == 9 {
+					reachableNines++
+				}
+			}
+		}
+	}
+
+	return reachableNines
+}

+ 0 - 0
aoc2024/day10/day10.py


+ 8 - 0
aoc2024/day10/example.txt

@@ -0,0 +1,8 @@
+89010123
+78121874
+87430965
+96549874
+45678903
+32019012
+01329801
+10456732

+ 42 - 0
aoc2024/day10/input.txt

@@ -0,0 +1,42 @@
+652101223431010123212787018120123432102123
+743012214321123434303692189011014501343012
+898129805010698543214543274320329691256765
+210036776234567690165567865411298780269834
+378945689103698789876458976502332109100121
+463210187892789870122345689965423458236780
+554109096701098565031018769876210967745698
+695678125432145678540019810567305870894327
+788987030120130989654321001498456701765016
+018976546543221078765478212312565432120145
+327348987012344569876569801108976789013237
+456256780109853078903478412217789676567898
+216107891238762169012894323306587987401298
+307898994345667654321765401455496096300347
+456767287454108991210101232960345145212456
+378950106543211280890810345871232234336765
+567843217017870376721987496432821101123898
+454107898726965445432896587501910787034567
+303210789634231030567801457601801896543298
+211023676540142121056932368212769787432109
+072124545035658762346541079345678891001876
+189433032123769654390670988454501762018967
+276542121054898323481787643367432053323458
+345633654765433210672696652298749144310549
+498726547890121306543545781121878235699632
+765017630987010129401235690030965456788701
+834198921256100438767624510549854307890123
+920183210343221245658913025678123210019834
+813274101254234986541002134765089876521765
+104565431069145875632101098834456785430345
+211278922378036780749812367903321896101216
+810189810467929891898701456512010787236707
+983210123567810432325600210105677698945898
+874301034512345587014511343234988767650789
+765212965403476696523329858943439656501090
+650163874301984785489834767652034565432781
+543254989218943210390765789621129210345652
+432167878307654101281087656780098761231243
+545089861056743105672390543890145687650987
+456778352149892234365401232763230896501276
+327863243434501345696543201054221245434345
+018954100123410210787894102343101230123656