-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathfaster_part1.py
executable file
·90 lines (66 loc) · 1.58 KB
/
faster_part1.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
#
# Faster part 1 algorithm scanning the entire grid only 4 times (once per
# direction), thus achieving a computational complexity of O(n^2) operations.
#
import sys
# Open the first argument as input or use stdin if no arguments were given
fin = open(sys.argv[1], 'rb') if len(sys.argv) > 1 else sys.stdin.buffer
with fin:
grid = fin.read().splitlines()
height, width = len(grid), len(grid[0])
maxr, maxc = height - 1, width - 1
visible = set()
for r in range(height):
tallest = -1
# West to East
for c in range(width):
tree = grid[r][c]
if tree > tallest:
tallest = tree
visible.add((r, c))
tallest = -1
# East to West
for c in range(maxr, -1, -1):
tree = grid[r][c]
if tree > tallest:
tallest = tree
visible.add((r, c))
for c in range(width):
tallest = -1
# North to South
for r in range(height):
tree = grid[r][c]
if tree > tallest:
tallest = tree
visible.add((r, c))
tallest = -1
# South to North
for r in range(maxc, -1, -1):
tree = grid[r][c]
if tree > tallest:
tallest = tree
visible.add((r, c))
n_visible = len(visible)
print('Part 1:', n_visible)
best = 0
for r in range(1, maxr):
row = grid[r]
for c in range(1, maxc):
tree = row[c]
for e in range(c + 1, width):
if row[e] >= tree:
break
for w in range(c - 1, -1, -1):
if row[w] >= tree:
break
for s in range(r + 1, height):
if grid[s][c] >= tree:
break
for n in range(r - 1, -1, -1):
if grid[n][c] >= tree:
break
score = (e - c) * (c - w) * (s - r) * (r - n)
if score > best:
best = score
print('Part 2:', best)