99 lines
1.9 KiB
Lua
99 lines
1.9 KiB
Lua
io.input("test")
|
|
io.input("input")
|
|
|
|
function addTree( r, c, height )
|
|
local visible = nil
|
|
if r==1 or c==1 or r==n or c==n then
|
|
visible = true
|
|
end
|
|
local tree = { h = height, v = visible, s = 1 }
|
|
trees[r][c] = tree
|
|
return tree
|
|
end
|
|
|
|
trees = {}
|
|
n = 0
|
|
local row = 1
|
|
for line in io.lines() do
|
|
n = #line
|
|
local col = 1
|
|
trees[row] = {}
|
|
for height in string.gmatch(line, "%d") do
|
|
local tree = addTree( row, col, height )
|
|
if row>1 and col>1 then
|
|
local allLess = true
|
|
local s = 0
|
|
for r=row-1,1,-1 do
|
|
s = s+1
|
|
if trees[r][col].h >= tree.h then
|
|
allLess = false
|
|
break
|
|
end
|
|
end
|
|
if allLess then tree.v = true end
|
|
tree.s = s*tree.s
|
|
|
|
allLess = true
|
|
s = 0
|
|
for c=col-1,1,-1 do
|
|
s = s + 1
|
|
if trees[row][c].h >= tree.h then
|
|
allLess = false
|
|
break
|
|
end
|
|
end
|
|
if allLess then tree.v = true end
|
|
tree.s = s*tree.s
|
|
end
|
|
col = col + 1
|
|
end
|
|
row = row + 1
|
|
end
|
|
|
|
-- second pass, other direction
|
|
for row = n-1, 2, -1 do
|
|
for col = n-1, 2, -1 do
|
|
local tree = trees[row][col]
|
|
local allLess = true
|
|
local s = 0
|
|
for r=row+1,n do
|
|
s = s + 1
|
|
if trees[r][col].h >= tree.h then
|
|
allLess = false
|
|
break
|
|
end
|
|
end
|
|
if allLess then tree.v = true end
|
|
tree.s = tree.s*s
|
|
|
|
allLess = true
|
|
s = 0
|
|
for c=col+1,n do
|
|
s = s + 1
|
|
if trees[row][c].h >= tree.h then
|
|
allLess = false
|
|
break
|
|
end
|
|
end
|
|
if allLess then tree.v = true end
|
|
tree.s = tree.s*s
|
|
|
|
end
|
|
end
|
|
|
|
local sum = 0
|
|
local maxscore = 0
|
|
for i, row in ipairs(trees) do
|
|
for j, tree in ipairs(row) do
|
|
-- part 1
|
|
if tree.v then sum = sum + 1 end
|
|
-- part 2
|
|
if tree.s > maxscore and i>1 and i<n and j>1 and j<n then
|
|
maxscore = tree.s
|
|
end
|
|
end
|
|
end
|
|
|
|
print("part 1", sum )
|
|
print("part 2", maxscore )
|