File size: 1,913 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
def solve():
    file = "input.txt"
    grid = []
    with open(file, 'r') as f:
        for line in f:
            grid.append(list(line.strip()))

    rows = len(grid)
    cols = len(grid[0])

    def find_guard():
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == '^':
                    return r, c, 0  # row, col, direction (0: up, 1: right, 2: down, 3: left)

    def is_valid(r, c):
        return 0 <= r < rows and 0 <= c < cols

    def move_guard(r, c, direction):
        dr = [-1, 0, 1, 0]
        dc = [0, 1, 0, -1]

        nr, nc = r + dr[direction], c + dc[direction]
        if is_valid(nr, nc) and grid[nr][nc] != '#':
            return nr, nc, direction
        else:
            return r, c, (direction + 1) % 4

    # Part 1
    visited = set()
    r, c, direction = find_guard()
    while is_valid(r, c):
        visited.add((r, c))
        r, c, direction = move_guard(r, c, direction)
    print(len(visited))


    # Part 2
    def simulate_with_obstacle(obstacle_r, obstacle_c):
        temp_grid = [row[:] for row in grid]
        temp_grid[obstacle_r][obstacle_c] = '#'
        visited = set()
        r, c, direction = find_guard()
        while (r,c) not in visited and is_valid(r,c):
            visited.add((r,c))
            
            dr = [-1, 0, 1, 0]
            dc = [0, 1, 0, -1]

            nr, nc = r + dr[direction], c + dc[direction]
            if is_valid(nr, nc) and temp_grid[nr][nc] != '#':
                r,c = nr,nc
            else:
                direction = (direction + 1) % 4
        return (r,c) in visited

    loop_count = 0
    start_r, start_c, _ = find_guard()
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '.' and (r, c) != (start_r, start_c):
                if simulate_with_obstacle(r, c):
                    loop_count += 1
    print(loop_count)

solve()