check cost validity before entering in pq

This commit is contained in:
Felix Van der Jeugt 2021-12-15 11:30:14 +01:00
parent 8fe19e4643
commit e5d2beb9e0
No known key found for this signature in database
GPG Key ID: 58B209295023754D

View File

@ -33,16 +33,14 @@ local distances = {}
local n = { 1, 1, 0 } local n = { 1, 1, 0 }
while n ~= nil and (distances[5*h] == nil or distances[5*h][5*w] == nil) do while n ~= nil and (distances[5*h] == nil or distances[5*h][5*w] == nil) do
local r, c, d = unpack(n) local r, c, d = unpack(n)
if cost(r, c) < math.huge then local row = distances[r] or {}
local row = distances[r] or {} if d < (row[c] or math.huge) then
if d < (row[c] or math.huge) then row[c] = d
row[c] = d distances[r] = row
distances[r] = row if cost(r-1, c) < math.huge then pq:add({ r-1, c, d + cost(r-1, c) }) end
pq:add({ r-1, c, d + cost(r-1, c) }) if cost(r, c-1) < math.huge then pq:add({ r, c-1, d + cost(r, c-1) }) end
pq:add({ r, c-1, d + cost(r, c-1) }) if cost(r+1, c) < math.huge then pq:add({ r+1, c, d + cost(r+1, c) }) end
pq:add({ r+1, c, d + cost(r+1, c) }) if cost(r, c+1) < math.huge then pq:add({ r, c+1, d + cost(r, c+1) }) end
pq:add({ r, c+1, d + cost(r, c+1) })
end
end end
n = pq:pop() n = pq:pop()
end end