import re
from tracemalloc import start
import numpy as np


list_of_nodes = []



# f = open('test.txt', 'r')
f = open('input.txt', 'r')
content = f.read()
lines = content.splitlines()

my_grid = np.array(lines)

universe_list = []

for line_count, line in enumerate(lines):
    # finds = line.find_all("#")
    # for find in finds:
    #     locations.append([line_count, find])
    line_list = []
    for ch in line:
        line_list.append(int(ch))
    
    universe_list.append(line_list)

universe = np.array(universe_list)
W = len(universe[0])
H = len(universe[1])

VISITED = {}

best = 10000000

finished = False
list_of_nodes.append([[0,0],[1,0],0])
list_of_nodes.append([[0,0],[0,1],0])
while not finished:
    print("Cycle")
    min_node = list_of_nodes.pop(0)
    for i in range(3):
        #change direction
        if i >= 1-1:
            for j in [-1,1]:
                dir = [j*min_node[1][1], j*min_node[1][0]]
                pos = [min_node[0][0] + dir[0], min_node[0][1] + dir[1]]
                if pos[0] >= 0 and pos[0] < W and pos[1] >= 0 and pos[1] < H:
                    heat = min_node[2] + universe[pos[0]][pos[1]]
                    key = (*pos, *dir)
                    if (key in VISITED and VISITED[key] <= heat):
                        continue
                    else:
                        list_of_nodes.append([pos, dir, heat])
                        if pos == [W-1, H-1]:
                            if heat < best:
                                best = heat
                        VISITED[key] = heat
                
        min_node[0] = [min_node[0][0] + min_node[1][0], min_node[0][1] + min_node[1][1]]
        if min_node[0][0] >= 0 and min_node[0][0] < W and min_node[0][1] >= 0 and min_node[0][1] < H:
            min_node[2] = min_node[2] + universe[min_node[0][0]][min_node[0][1]]
            if min_node[0] == [W-1, H-1]:
                if min_node[2] < best:
                    best = min_node[2]
        else:
            break
            
    list_of_nodes.sort(key = lambda x: x[2])
    finished = (len(list_of_nodes) == 0 or list_of_nodes[0][0] == [W-1, H-1])
    
print(best)
# print(universe)
print(list_of_nodes[0][2])
# print(VISITED[(W-1, H-1, 0,1)])
# print(VISITED[(W-1, H-1, 1,0)])
sum = 0





f.close()