From 84c7f424ba7ac8ff833ed0974fff1befeafda090 Mon Sep 17 00:00:00 2001 From: Parnic Date: Wed, 15 Dec 2021 12:15:31 -0600 Subject: [PATCH] >2x speedup for part 2 Based on a suggestion from @tocchan I converted the total risk map from a Dictionary to an array and things really took off (125ms to 50ms on my machine in Release). And that's with a sub-optimal fill/memset of the array to int.MaxValue (which I couldn't find a better way to do without diving into `unsafe` territory), though that step only takes about 500us with this method anyway, so it's hardly the worst part. --- src/15.cs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/15.cs b/src/15.cs index b511660..6dbd5c3 100644 --- a/src/15.cs +++ b/src/15.cs @@ -42,30 +42,36 @@ internal class Day15 : Day private static int Solve(byte[,] riskMap) { var start = (x: 0, y: 0); - var end = (x: riskMap.GetLength(0) - 1, y: riskMap.GetLength(1) - 1); + var (xDim, yDim) = (riskMap.GetLength(0), riskMap.GetLength(1)); + var end = (x: xDim - 1, y: yDim - 1); var q = new PriorityQueue<(int, int), int>(); q.Enqueue(start, 0); - var totalRiskMap = new Dictionary<(int, int), int> + var totalRiskMap = new int[xDim, yDim]; + for (int x = 0; x < xDim; x++) { - [start] = 0 - }; + for (int y = 0; y < yDim; y++) + { + totalRiskMap[x, y] = int.MaxValue; + } + } + totalRiskMap[start.x, start.y] = 0; for (var currPoint = start; currPoint != end; currPoint = q.Dequeue()) { foreach (var adjacent in Adjacent(riskMap, currPoint.x, currPoint.y)) { - var totalRiskThroughP = totalRiskMap[currPoint] + riskMap[adjacent.x, adjacent.y]; - if (totalRiskThroughP < totalRiskMap.GetValueOrDefault(adjacent, int.MaxValue)) + var totalRiskThroughP = totalRiskMap[currPoint.x, currPoint.y] + riskMap[adjacent.x, adjacent.y]; + if (totalRiskThroughP < totalRiskMap[adjacent.x, adjacent.y]) { - totalRiskMap[adjacent] = totalRiskThroughP; + totalRiskMap[adjacent.x, adjacent.y] = totalRiskThroughP; q.Enqueue(adjacent, totalRiskThroughP); } } } - return totalRiskMap[end]; + return totalRiskMap[end.x, end.y]; } private static void Part1(byte[,] grid)