import sys import heapq def MI(): return map(int,sys.stdin.readline().rstrip().split()) N,M = MI() HWC = [tuple(MI()) for _ in range(M)] Graph = [[] for _ in range(N**2)] for i in range(N): for j in range(N-1): a,b = N*i+j,N*i+j+1 Graph[a].append([b,1]) Graph[b].append([a,1]) for i in range(N-1): for j in range(N): a,b = N*i+j,N*(i+1)+j Graph[a].append([b,1]) Graph[b].append([a,1]) for h,w,c in HWC: h -= 1 w -= 1 b = N*h+w if h >= 1: a = N*(h-1)+w Graph[a] = [x for x in Graph[a] if x[0] != b]+[[b,c+1]] if h <= N-2: a = N*(h+1)+w Graph[a] = [x for x in Graph[a] if x[0] != b]+[[b,c+1]] if w >= 1: a = N*h+w-1 Graph[a] = [x for x in Graph[a] if x[0] != b]+[[b,c+1]] if w <= N-2: a = N*h+w+1 Graph[a] = [x for x in Graph[a] if x[0] != b]+[[b,c+1]] inf = 10**18 dist0 = [inf]*(N**2) # (1,1)からの最短距離 dist0[0] = 0 q0 = [] heapq.heappush(q0,(0,0)) v0 = [0]*(N**2) while q0: k,u = heapq.heappop(q0) if v0[u]: continue v0[u] = True for x in Graph[u]: uv,ud = x if v0[uv]: continue vd = k + ud if dist0[uv] > vd: dist0[uv] = vd heapq.heappush(q0,(vd,uv)) dist1 = [inf]*(N**2) # (N,N)からの最短距離 dist1[N**2-1] = 0 q1 = [] heapq.heappush(q1,(0,N**2-1)) v1 = [0]*(N**2) while q1: k,u = heapq.heappop(q1) if v1[u]: continue v1[u] = True for x in Graph[u]: uv,ud = x if v1[uv]: continue vd = k + ud if dist1[uv] > vd: dist1[uv] = vd heapq.heappush(q1,(vd,uv)) ans = dist0[-1] for h,w,c in HWC: h -= 1 w -= 1 a = N*h+w ans = min(ans,dist0[a]+dist1[a]-2*c) print(ans)