generalize union find

This commit is contained in:
Felix Van der Jeugt 2021-12-09 11:30:02 +01:00
parent ef0775f5e2
commit e058039f35
No known key found for this signature in database
GPG key ID: 58B209295023754D
2 changed files with 40 additions and 35 deletions

View file

@ -10,6 +10,7 @@ for line in io.lines(arg[3]) do
end
table.insert(hm, row)
end
local w = #hm[1]
local function get(r, c)
return (hm[r] or {})[c] or 9
@ -20,19 +21,22 @@ 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, c)
union:makeset(r - 1, c)
union:union(r, c, r - 1, c)
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, c)
union:makeset(r, c - 1)
union:union(r, c, r, c - 1)
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 = union:sizes()
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])