from heapq import heapify, heappop, heappush N,M = map(int,input().split()); INF = float("inf") dic = {} for i in range(M): h,w,c = map(int,input().split()) h-=1;w-=1 dic[h*N+w] = c #print(dic) G = [[] for _ in range(N*N)] dxdy = [(0,1),(0,-1),(1,0),(-1,0)] for i in range(N): for j in range(N): now = i*N + j for k in range(4): ni = i+dxdy[k][0] nj = j+dxdy[k][1] if 0<=ni= V: oriv = v - V else: oriv = v for cost,u in G[oriv]: if v < V: #未行使 if d[u] <= cost + d[v]: pass else: d[u] = cost + d[v] heappush(PQ,(d[u], u)) if d[u+V] <= 1 + d[v]: #移動の1は必ずかかる。 pass else: d[u+V] = 1 + d[v] heappush(PQ,(d[u+V], u+V)) else: #行使済み if d[u+V] <= cost + d[v]: pass else: d[u+V] = cost + d[v] heappush(PQ,(d[u+V], u+V)) return d D = dijkstra_heap2(0,G) #print(D) ans = min(D[N*N-1],D[2*N*N-1]) print(ans)