INF = 1e18 from heapq import heappop, heappush def main(): N, M = map(int, input().split()) def check(i, j): return 0 <= i < N and 0 <= j < N memo = [[0] * (N) for _ in range(N)] for i in range(M): h, w, c = map(int, input().split()) h -= 1 w -= 1 memo[h][w] = c kakutei = [[[False] * (2) for _ in range(N)] for _ in range(N)] cost = [[[INF] * (2) for _ in range(N)] for _ in range(N)] cost[0][0][0] = 0 que = [] heappush(que, (0, 0, 0, 0)) # cost_cur, i, j, k while que: curr_cost, i, j, k = heappop(que) if kakutei[i][j][k]: continue kakutei[i][j][k] = True for ii, jj in [(0, -1), (0, 1), (-1, 0), (1, 0)]: ni, nj = i+ii, j+jj if not check(ni, nj): continue # 同じ高さ if cost[ni][nj][k] > curr_cost + memo[ni][nj] + 1: cost[ni][nj][k] = curr_cost + memo[ni][nj] + 1 heappush(que, (cost[ni][nj][k], ni, nj, k)) if k == 0 and cost[ni][nj][1] > curr_cost + 1: cost[ni][nj][1] = curr_cost + 1 heappush(que, (cost[ni][nj][1], ni, nj, 1)) print(min(cost[-1][-1])) if __name__ == "__main__": main()