From e5d2beb9e075e4c1bbda5ca54dc402c4a5916784 Mon Sep 17 00:00:00 2001 From: Felix Van der Jeugt Date: Wed, 15 Dec 2021 11:30:14 +0100 Subject: [PATCH] check cost validity before entering in pq --- day15/part2.lua | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/day15/part2.lua b/day15/part2.lua index 1a5acde..60cc4a3 100755 --- a/day15/part2.lua +++ b/day15/part2.lua @@ -33,16 +33,14 @@ local distances = {} local n = { 1, 1, 0 } while n ~= nil and (distances[5*h] == nil or distances[5*h][5*w] == nil) do local r, c, d = unpack(n) - if cost(r, c) < math.huge then - local row = distances[r] or {} - if d < (row[c] or math.huge) then - row[c] = d - distances[r] = row - pq:add({ r-1, c, d + cost(r-1, c) }) - pq:add({ r, c-1, d + cost(r, c-1) }) - pq:add({ r+1, c, d + cost(r+1, c) }) - pq:add({ r, c+1, d + cost(r, c+1) }) - end + local row = distances[r] or {} + if d < (row[c] or math.huge) then + row[c] = d + distances[r] = row + if cost(r-1, c) < math.huge then pq:add({ r-1, c, d + cost(r-1, c) }) end + if cost(r, c-1) < math.huge then pq:add({ r, c-1, d + cost(r, c-1) }) end + if cost(r+1, c) < math.huge then pq:add({ r+1, c, d + cost(r+1, c) }) end + if cost(r, c+1) < math.huge then pq:add({ r, c+1, d + cost(r, c+1) }) end end n = pq:pop() end