adventofcode-2021/day09/part2.lua
2021-12-09 11:30:02 +01:00

43 lines
836 B
Lua
Executable File

#!/usr/bin/env luajit
require("utils")
require("unionfind")
local hm = {}
for line in io.lines(arg[3]) do
local row = {}
for c in chars(line) do
table.insert(row, tonumber(c))
end
table.insert(hm, row)
end
local w = #hm[1]
local function get(r, c)
return (hm[r] or {})[c] or 9
end
local union = unionfind()
for r, row in pairs(hm) do
for c, col in pairs(row) do
if col ~= 9 then
if get(r - 1, c) ~= 9 then
union:makeset(r*w + c)
union:makeset(r*w - w + c)
union:union(r*w + c, r*w - w + c)
end
if get(r, c - 1) ~= 9 then
union:makeset(r*w + c)
union:makeset(r*w + c - 1)
union:union(r*w + c, r*w + c - 1)
end
end
end
end
local sizes = {}
for set, size in union:unions() do
table.insert(sizes, size)
end
table.sort(sizes)
print(sizes[#sizes] * sizes[#sizes - 1] * sizes[#sizes - 2])