def count_timelines(grid): # Dynamic programming my beloved/behated num_rows = len(grid) num_cols = len(grid[0]) counts = [1 if grid[0][c] == 'S' else 0 for c in range(num_cols)] for r in range(num_rows): next_counts = [0] * num_cols row = grid[r] for c in range(num_cols): k = counts[c] if k == 0: continue if row[c] == '^': if c > 0: next_counts[c - 1] += k if c + 1 < num_cols: next_counts[c + 1] += k else: next_counts[c] += k counts = next_counts return sum(counts) with open('input.txt', 'r') as f: lines = [line.rstrip('\n') for line in f] grid = [list(line) for line in lines] total = count_timelines(grid) print(total)