-
-
Save gnyman/b8b6b3775b075cbe21fa6553ac260194 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def count_visible_trees(filename): | |
# Open the file and read the lines into a list | |
with open(filename) as f: | |
grid = f.readlines() | |
# Parse the input and create a 2D list of integers | |
grid = [[int(ch) for ch in row.strip()] for row in grid] | |
# Initialize the count of visible trees | |
count = 0 | |
# Iterate over the elements of the grid | |
for row in range(len(grid)): | |
for col in range(len(grid[0])): | |
# Check if the current element is on the edge of the grid | |
if row == 0 or row == len(grid)-1 or col == 0 or col == len(grid[0])-1: | |
count += 1 | |
else: | |
# Check if there are any taller trees blocking the view | |
# of the current element in any direction | |
if max([grid[row-1][col], grid[row+1][col], grid[row][col-1], grid[row][col+1]], default=grid[row][col]) <= grid[row][col]: | |
count += 1 | |
# Return the count of visible trees | |
return count | |
filename = "sample.txt" | |
count = count_visible_trees(filename) | |
print(count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment