Advertisement
Guest User

Untitled

a guest
Dec 9th, 2024
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | Source Code | 0 0
  1. from collections import deque
  2.  
  3. path = "day_10.txt"
  4. # path = "test.txt"
  5.  
  6. directions = [
  7.     (0, -1),
  8.     (1, 0),
  9.     (0, 1),
  10.     (-1, 0)
  11. ]
  12.  
  13. with open(path) as f:
  14.     lines = [l.strip() for l in f.readlines()]
  15.    
  16.  
  17. ROWS = len(lines)
  18. COLS = len(lines[0])
  19.  
  20. trail_heads = []
  21. for row in range(ROWS):
  22.     for col in range(COLS):
  23.         tile = lines[row][col]
  24.         if tile.isnumeric() and int(tile) == 0:
  25.             trail_heads.append((row,col))
  26.  
  27. def is_inside(grid, row, col):
  28.     return 0 <= row < len(grid) and 0 <= col < len(grid[0])
  29.  
  30. total = 0
  31.  
  32. def count_score(grid, trail_head, part_2):
  33.     score = 0
  34.     visited_ends = set()
  35.     tiles = [trail_head]
  36.    
  37.     while len(tiles) > 0:
  38.         row, col = tiles.pop()
  39.         height = int(grid[row][col])
  40.        
  41.         if (part_2 or (row, col) not in visited_ends) and height == 9:
  42.             score += 1
  43.             visited_ends.add((row, col))
  44.             continue
  45.        
  46.         for r, c in directions:
  47.             new_row = row + r
  48.             new_col = col + c
  49.             if is_inside(grid, new_row, new_col) and int(grid[new_row][new_col]) - height == 1:
  50.                 tiles.append((new_row, new_col))
  51.            
  52.     return score
  53.  
  54. print("p1:", sum([count_score(lines, i, False) for i in trail_heads]))
  55. print("p2:", sum([count_score(lines, i, True) for i in trail_heads]))
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement