Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 8, 2022 12:25
Embed
What would you like to do?
import sys
# Read the input from the command line argument
with open(sys.argv[1], "r") as file:
# Read the input as a list of strings
grid = file.read().strip().split("\n")
# Convert the strings to a list of lists of integers
grid = [[int(ch) for ch in row] for row in grid]
# Get the number of rows and columns in the grid
num_rows = len(grid)
num_cols = len(grid[0])
# Initialize the number of visible trees to 0
num_visible = 0
# Loop through each row and column of the grid
for i in range(num_rows):
for j in range(num_cols):
# Get the height of the current tree
height = grid[i][j]
# Check if the tree is on the edge of the grid
is_on_edge = i == 0 or i == num_rows - 1 or j == 0 or j == num_cols - 1
# Check if the tree is visible from the left
if (j == 0 or height > grid[i][j - 1]) and not is_on_edge:
num_visible += 1
# Check if the tree is visible from the right
if (j == num_cols - 1 or height > grid[i][j + 1]) and not is_on_edge:
num_visible += 1
# Check if the tree is visible from the top
if (i == 0 or height > grid[i - 1][j]) and not is_on_edge:
num_visible += 1
# Check if the tree is visible from the bottom
if (i == num_rows - 1 or height > grid[i + 1][j]) and not is_on_edge:
num_visible += 1
# Print the number of visible trees
print(num_visible)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment