from collections import deque INF = float('inf') N, M = map(int, input().split()) c = [[0] * N for _ in range(N)] for _ in range(M): h, w, cc = map(int, input().split()) c[h - 1][w - 1] = cc dp = [[(INF, 0)] * N for _ in range(N)] dp[0][0] = (0, 0) q = deque([(0, 0)]) while q: h, w = q.popleft() t, m = dp[h][w] if h != 0: a, b = dp[h - 1][w] d = t + 1 + c[h - 1][w] e = max(m, c[h - 1][w]) if d - e < a - b: dp[h - 1][w] = (d, e) q.append((h - 1, w)) if h != N - 1: a, b = dp[h + 1][w] d = t + 1 + c[h + 1][w] e = max(m, c[h + 1][w]) if d - e < a - b: dp[h + 1][w] = (d, e) q.append((h + 1, w)) if w != 0: a, b = dp[h][w - 1] d = t + 1 + c[h][w - 1] e = max(m, c[h][w - 1]) if d - e < a - b: dp[h][w - 1] = (d, e) q.append((h, w - 1)) if w != N - 1: a, b = dp[h][w + 1] d = t + 1 + c[h][w + 1] e = max(m, c[h][w + 1]) if d - e < a - b: dp[h][w + 1] = (d, e) q.append((h, w + 1)) t, m = dp[N - 1][N - 1] print(t - m)