From ce6e63b5b6c50b65b419577999365aef1f9ad5eb Mon Sep 17 00:00:00 2001 From: Parnic Date: Mon, 13 Jun 2022 08:31:43 -0500 Subject: [PATCH] Day 15 Part 2 Well...that turned out easier than I thought. I suspected this solution would work, but wasn't completely confident. It can only work for the type of maze used by this problem (where there are no loops of open areas). --- days/15.go | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/days/15.go b/days/15.go index ef8f4d0..8c11a24 100644 --- a/days/15.go +++ b/days/15.go @@ -5,6 +5,7 @@ package days import ( "fmt" "math" + "sort" u "parnic.com/aoc2019/utilities" ) @@ -99,6 +100,17 @@ func (d Day15) getCellTypeInDirection(pos point, dir dirType) (cellStatus, point return d.grid[target], target } +func (d Day15) getAdjacentCellsOfType(pos point, cellType cellStatus) []point { + points := make([]point, 0, 4) + for i := dirFirst; i <= dirLast; i++ { + adjacentCell := d.getPointInDirection(pos, i) + if d.grid[adjacentCell] == cellType { + points = append(points, adjacentCell) + } + } + return points +} + func (d Day15) getDirToNextCellType(pos point, t cellStatus, maxNumVisited int, dirs []dirType) (dirType, point, error) { for _, dir := range dirs { cellInDirection, targetCell := d.getCellTypeInDirection(pos, dir) @@ -284,6 +296,16 @@ func (d *Day15) exploreFullMap() map[point]*visitedStatus { return goalVisited } +func (d *Day15) tagDistanceRecursive(pos, last point, dist int, distances map[point]int) { + distances[pos] = dist + for _, cell := range d.getAdjacentCellsOfType(pos, cellStatusOpen) { + if cell == last { + continue + } + d.tagDistanceRecursive(cell, pos, dist+1, distances) + } +} + func (d *Day15) Part1() string { d.visited = d.exploreFullMap() d.markShortestPath() @@ -298,5 +320,13 @@ func (d *Day15) Part1() string { } func (d *Day15) Part2() string { - return fmt.Sprintf("%s%d%s", u.TextBold, 0, u.TextReset) + startLoc := d.goalPos + distanceMap := map[point]int{startLoc: 0} + + d.tagDistanceRecursive(startLoc, point{}, 0, distanceMap) + + cellDistances := u.MapValues(distanceMap) + sort.Slice(cellDistances, func(i, j int) bool { return cellDistances[i] > cellDistances[j] }) + + return fmt.Sprintf("%s%d%s", u.TextBold, cellDistances[0], u.TextReset) }