96 lines
1.9 KiB
Python
96 lines
1.9 KiB
Python
|
import math
|
||
|
|
||
|
ex_data = """30373
|
||
|
25512
|
||
|
65332
|
||
|
33549
|
||
|
35390"""
|
||
|
with open("08.txt") as f:
|
||
|
data = f.read()
|
||
|
|
||
|
def get_arr(data):
|
||
|
arr = dict()
|
||
|
lines = data.splitlines()
|
||
|
h = len(lines)
|
||
|
w = len(lines[0])
|
||
|
|
||
|
for y, line in enumerate(lines):
|
||
|
line = line.strip()
|
||
|
for x, c in enumerate(line):
|
||
|
arr[x, y] = int(c)
|
||
|
return arr, w, h
|
||
|
|
||
|
def solve1(data):
|
||
|
arr, w, h = get_arr(data)
|
||
|
|
||
|
default_m = -1
|
||
|
|
||
|
def from_top(f):
|
||
|
for x in range(w):
|
||
|
m = default_m
|
||
|
for y in range(h):
|
||
|
m = f(x, y, m)
|
||
|
def from_bottom(f):
|
||
|
for x in range(w):
|
||
|
m = default_m
|
||
|
for y in range(h - 1, -1, -1):
|
||
|
m = f(x, y, m)
|
||
|
def from_left(f):
|
||
|
for y in range(h):
|
||
|
m = default_m
|
||
|
for x in range(w):
|
||
|
m = f(x, y, m)
|
||
|
def from_right(f):
|
||
|
for y in range(h):
|
||
|
m = default_m
|
||
|
for x in range(w - 1, -1, -1):
|
||
|
m = f(x, y, m)
|
||
|
|
||
|
dirs = [from_top, from_bottom, from_left, from_right]
|
||
|
visible = set()
|
||
|
|
||
|
def collect(x, y, m):
|
||
|
if arr[x, y] <= m: return m
|
||
|
visible.add((x, y))
|
||
|
return arr[x, y]
|
||
|
|
||
|
for func in dirs: func(collect)
|
||
|
print(len(visible))
|
||
|
|
||
|
def solve2(data):
|
||
|
arr, w, h = get_arr(data)
|
||
|
|
||
|
dirs = {(0, 1), (1, 0), (0, -1), (-1, 0)}
|
||
|
max_score = 0
|
||
|
|
||
|
for x in range(w):
|
||
|
for y in range(h):
|
||
|
components = []
|
||
|
for (dx, dy) in dirs:
|
||
|
coords_in_dir = []
|
||
|
for i in range(1, max(w, h)):
|
||
|
coord = (x + i * dx, y + i * dy)
|
||
|
if coord in arr: coords_in_dir.append(coord)
|
||
|
if len(coords_in_dir) == 0:
|
||
|
components.append(0)
|
||
|
continue
|
||
|
|
||
|
trees = 0
|
||
|
for coord in coords_in_dir:
|
||
|
height = arr[coord]
|
||
|
trees += 1
|
||
|
if height >= arr[x, y]:
|
||
|
break
|
||
|
components.append(trees)
|
||
|
scenic_score = math.prod(components)
|
||
|
max_score = max(max_score, scenic_score)
|
||
|
# print(x, y, components, scenic_score, max_score)
|
||
|
|
||
|
print(max_score)
|
||
|
|
||
|
solve1(ex_data)
|
||
|
solve1(data)
|
||
|
|
||
|
solve2(ex_data)
|
||
|
solve2(data)
|