48 lines
1.0 KiB
Lua
Executable File
48 lines
1.0 KiB
Lua
Executable File
#!/usr/bin/env luajit
|
|
require("utils")
|
|
require("pqueue")
|
|
|
|
local grid = {}
|
|
for line in io.lines(arg[3]) do
|
|
local row = {}
|
|
for char in chars(line) do
|
|
table.insert(row, tonumber(char))
|
|
end
|
|
table.insert(grid, row)
|
|
end
|
|
|
|
function printgrid()
|
|
for r, row in pairs(grid) do
|
|
for c, cell in pairs(row) do
|
|
io.write(string.format("%3d", cell))
|
|
end
|
|
io.write('\n')
|
|
end
|
|
end
|
|
|
|
local pq = pqueue(function(a, b)
|
|
return a[3] < b[3]
|
|
end)
|
|
|
|
local distances = {}
|
|
|
|
local H = math.huge
|
|
local n = { 1, 1, 0 }
|
|
while n ~= nil and (distances[#grid] == nil or distances[#grid][#grid[1]] == nil) do
|
|
local r, c, d = unpack(n)
|
|
if 0 < r or r <= #grid or 0 < c or c <= #grid[r] then
|
|
local row = distances[r] or {}
|
|
if d < (row[c] or H) then
|
|
row[c] = d
|
|
distances[r] = row
|
|
pq:add({ r-1, c, d + ((grid[r-1] or {})[c] or H) })
|
|
pq:add({ r, c-1, d + ((grid[r] or {})[c-1] or H) })
|
|
pq:add({ r+1, c, d + ((grid[r+1] or {})[c] or H) })
|
|
pq:add({ r, c+1, d + ((grid[r] or {})[c+1] or H) })
|
|
end
|
|
end
|
|
n = pq:pop()
|
|
end
|
|
|
|
print(distances[#grid] and distances[#grid][#grid[1]])
|