import heapq debug=False def pprint(*s): if debug==True: print(*s) n,m=map(int,input().split()) fees={} for _ in range(m): y,x,cost=map(int,input().split()) fees[(x-1,y-1)]=cost INF=10**18 costs=[[[INF,INF] for _ in range(n)] for _ in range(n)] costs[0][0]=[0,0] q=[] heapq.heappush(q,(0,0,0,0)) while len(q)!=0: curcost,x,y,skipped=heapq.heappop(q) pprint('x:{},y:{},cost:{},skipped:{}'.format(x,y,curcost,skipped)) if x==n-1 and y==n-1: print(curcost) exit() for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]: if 0<=x+dx<=n-1 and 0<=y+dy<=n-1: if (x+dx,y+dy) in fees: if skipped==0: if costs[y+dy][x+dx][skipped+1]>curcost+1: heapq.heappush(q,(curcost+1,x+dx,y+dy,skipped+1)) costs[y+dy][x+dx][skipped+1]=curcost+1 if costs[y+dy][x+dx][skipped]>curcost+1+fees[(x+dx,y+dy)]: heapq.heappush(q,(curcost+1+fees[(x+dx,y+dy)],x+dx,y+dy,skipped)) costs[y+dy][x+dx][skipped]=curcost+1+fees[(x+dx,y+dy)] else: if costs[y+dy][x+dx][skipped]>curcost+1+fees[(x+dx,y+dy)]: heapq.heappush(q,(curcost+1+fees[(x+dx,y+dy)],x+dx,y+dy,skipped)) costs[y+dy][x+dx][skipped]=curcost+1+fees[(x+dx,y+dy)] else: if costs[y+dy][x+dx][skipped]>curcost+1: heapq.heappush(q,(curcost+1,x+dx,y+dy,skipped)) costs[y+dy][x+dx][skipped]=curcost+1