from collections import deque def solve(): file = "input.txt" grid = [] with open(file, 'r') as f: for line in f: grid.append([int(x) for x in line.strip()]) rows = len(grid) cols = len(grid[0]) def get_neighbors(r, c): neighbors = [] for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: neighbors.append((nr, nc)) return neighbors def dfs_score(r, c): score = 0 visited = set() stack = [(r, c)] while stack: curr_r, curr_c = stack.pop() if (curr_r, curr_c) in visited: continue visited.add((curr_r, curr_c)) if grid[curr_r][curr_c] == 9: score += 1 continue for nr, nc in get_neighbors(curr_r, curr_c): if grid[nr][nc] == grid[curr_r][curr_c] + 1: stack.append((nr, nc)) return score def dfs_rating(r, c): rating = 0 stack = [([(r, c)], set())] while stack: path, visited = stack.pop() curr_r, curr_c = path[-1] if grid[curr_r][curr_c] == 9: rating += 1 continue for nr, nc in get_neighbors(curr_r, curr_c): if grid[nr][nc] == grid[curr_r][curr_c] + 1 and (nr, nc) not in visited: new_path = path + [(nr, nc)] new_visited = set(visited) new_visited.add((nr,nc)) stack.append((new_path, new_visited)) return rating total_score = 0 total_rating = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 0: total_score += dfs_score(r, c) total_rating += dfs_rating(r, c) print(total_score) print(total_rating) solve()