import re
from tracemalloc import start
import numpy as np


list_of_nodes = []



# f = open('test.txt', 'r')
# f = open('test2.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)
H = len(universe[0])
W = len(universe)

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:
    min_node = list_of_nodes.pop(0)
    for j in [-1, 1]:
        pos = min_node[0]
        heat = min_node[2]
        dir = [j*min_node[1][1], j*min_node[1][0]]
        for i in range(10):
        #change direction
            pos = [pos[0] + dir[0], pos[1] + dir[1]]
            if pos[0] >= 0 and pos[0] < W and pos[1] >= 0 and pos[1] < H:
                heat += universe[pos[0]][pos[1]]
                if i >= 4-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 = new_list
    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)
# print(VISITED[(W-1, H-1, 0,1)])
# print(VISITED[(W-1, H-1, 1,0)])
sum = 0





f.close()