#region Header #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools from queue import PriorityQueue import bisect import heapq def input(): return sys.stdin.readline()[:-1] sys.setrecursionlimit(1000000) #endregion # _INPUT = """3 2 # 2 2 100 # 2 3 200 # """ # sys.stdin = io.StringIO(_INPUT) def main(): N, M = map(int, input().split()) P = [[1 for _ in range(N)] for _ in range(N)] P[0][0] = 0 for _ in range(M): h, w, c = map(int, input().split()) h -= 1 w -= 1 P[h][w] = c + 1 dist = [[10**10 for _ in range(N)] for _ in range(N)] hq = [] heapq.heappush(hq, (0, (0, 0))) dist[0][0] = 0 path = [[None for _ in range(N)] for _ in range(N)] while hq: d, (h, w) = heapq.heappop(hq) if d > dist[h][w]: continue for (dh, dw) in [(-1, 0), (1, 0), (0, -1), (0, 1)]: (h1, w1) = (h + dh, w + dw) if 0 <= h1 <= N-1 and 0 <= w1 <= N-1: d1 = dist[h][w] + P[h1][w1] if d1 < dist[h1][w1]: dist[h1][w1] = d1 path[h1][w1] = (h, w) heapq.heappush(hq, (d1, (h1, w1))) M = 0 (h, w) = (N-1, N-1) while (h, w) != (0, 0): M = max(M, P[h][w]) (h, w) = path[h][w] print(dist[N-1][N-1] - (M - 1)) if __name__ == '__main__': main()