import sys input = sys.stdin.readline from heapq import * def dijkstra(): dist = [[[10**18]*N for _ in range(N)] for _ in range(2)] dist[0][0][0] = 0 pq = [] heappush(pq, (0, 0, 0, 0)) while pq: d, f, x, y = heappop(pq) if dist[f][x][y]dist[f][x][y]+cost[nx][ny]: dist[f][nx][ny] = dist[f][x][y]+cost[nx][ny] heappush(pq, (dist[f][nx][ny], f, nx, ny)) if f==0 and cost[nx][ny]>1 and dist[1][nx][ny]>dist[0][x][y]+1: dist[1][nx][ny] = dist[0][x][y]+1 heappush(pq, (dist[1][nx][ny], 1, nx, ny)) return min(dist[0][-1][-1], dist[1][-1][-1]) N, M = map(int, input().split()) cost = [[1]*N for _ in range(N)] for _ in range(M): h, w, c = map(int, input().split()) cost[h-1][w-1] += c print(dijkstra())