1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
local heights = {}
for line in io.lines() do
local trees = {}
line:gsub("%d",function(t)
local tree = {
height=tonumber(t),
visible={up=false,down=false,left=false,right=false},
}
table.insert(trees,tree)
end)
table.insert(heights,trees)
end
local nrow,ncol = #heights, #heights[1]
for i = 1,nrow do
heights[i][1].visible.left = true
heights[i][ncol].visible.right = true
end
for i = 1,ncol do
heights[1][i].visible.up = true
heights[nrow][i].visible.down = true
end
local total_visible = (nrow*2) + (ncol*2) - 4
local directions = {up={1,0},down={-1,0},left={0,1},right={0,-1}}
local function calc_visible(row,col)
local t = heights[row][col]
for name,direction in pairs(directions) do
local i,j = row - direction[1], col - direction[2]
while heights[i] and heights[i][j] do
if t.height > heights[i][j].height and heights[i][j].visible[name] then
t.visible[name] = true
break
elseif t.height <= heights[i][j].height then
t.visible[name] = false
break
end
i,j = i - direction[1], j - direction[2]
end
end
if t.visible.left or t.visible.right or t.visible.up or t.visible.down then
total_visible = total_visible + 1
end
end
for row = 2, nrow-1 do
for col = 2, ncol-1 do
calc_visible(row,col)
end
end
print(total_visible)
|