adventofcode-2021/day09/part2.lua

43 lines
836 B
Lua
Raw Normal View History

2021-12-09 09:21:55 +01:00
#!/usr/bin/env luajit
require("utils")
2021-12-09 09:59:20 +01:00
require("unionfind")
2021-12-09 09:21:55 +01:00
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
2021-12-09 11:30:02 +01:00
local w = #hm[1]
2021-12-09 09:21:55 +01:00
local function get(r, c)
return (hm[r] or {})[c] or 9
end
2021-12-09 09:59:20 +01:00
local union = unionfind()
2021-12-09 09:21:55 +01:00
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
2021-12-09 11:30:02 +01:00
union:makeset(r*w + c)
union:makeset(r*w - w + c)
union:union(r*w + c, r*w - w + c)
2021-12-09 09:21:55 +01:00
end
if get(r, c - 1) ~= 9 then
2021-12-09 11:30:02 +01:00
union:makeset(r*w + c)
union:makeset(r*w + c - 1)
union:union(r*w + c, r*w + c - 1)
2021-12-09 09:21:55 +01:00
end
end
end
end
2021-12-09 11:30:02 +01:00
local sizes = {}
for set, size in union:unions() do
table.insert(sizes, size)
end
2021-12-09 09:21:55 +01:00
table.sort(sizes)
print(sizes[#sizes] * sizes[#sizes - 1] * sizes[#sizes - 2])