#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 = """10 34 # 7 5 2286 # 2 2 3140 # 9 3 4600 # 9 6 5277 # 9 4 9057 # 1 6 1156 # 1 7 2356 # 6 10 2106 # 9 5 1192 # 4 6 9022 # 8 2 3221 # 8 9 7792 # 4 3 609 # 4 7 6593 # 2 6 3097 # 8 6 4348 # 2 10 213 # 7 3 7105 # 10 9 4412 # 6 4 4410 # 8 5 2870 # 2 5 2185 # 2 7 8469 # 7 10 3727 # 5 5 4076 # 10 6 2106 # 1 4 385 # 1 8 9753 # 6 7 3240 # 9 2 4081 # 3 7 4784 # 6 1 6748 # 5 10 6062 # 2 3 7218 # """ # sys.stdin = io.StringIO(_INPUT) def f(N, P): 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))) return dist[N-1][N-1] def main(): N, M = map(int, input().split()) P = [[1 for _ in range(N)] for _ in range(N)] P[0][0] = 0 points = [] for _ in range(M): h, w, c = map(int, input().split()) h -= 1 w -= 1 points.append((h, w, c)) P[h][w] = c + 1 n_min = 10**10 for i in range(M): h, w, c = points[i] P[h][w] = 1 n = f(N, P) n_min = min(n_min, n) P[h][w] = c + 1 print(n_min) if __name__ == '__main__': main()