File size: 1,975 Bytes
a4da721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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()