#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 7 # 1 2 5 # 1 3 8 # 2 1 7 # 2 2 3 # 2 3 9 # 3 1 11 # 3 2 2 # """ # 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 # dp[0] : 無料の権利を使っていない # dp[1] : 無料の権利を使った dp = [[[10**10 for _ in range(N)] for _ in range(N)] for _ in range(2)] hq = [] heapq.heappush(hq, (0, (0, 0, 0))) dp[0][0][0] = 0 dp[1][0][0] = 0 while hq: d, (flag, h, w) = heapq.heappop(hq) if d > dp[flag][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: if flag == 0: d1 = dp[0][h][w] + P[h1][w1] if d1 < dp[0][h1][w1]: dp[0][h1][w1] = d1 heapq.heappush(hq, (d1, (0, h1, w1))) d2 = dp[0][h][w] + 1 if d2 < dp[1][h1][w1]: dp[1][h1][w1] = d2 heapq.heappush(hq, (d2, (1, h1, w1))) else: d1 = dp[1][h][w] + P[h1][w1] if d1 < dp[1][h1][w1]: dp[1][h1][w1] = d1 heapq.heappush(hq, (d1, (1, h1, w1))) print(min(dp[0][N-1][N-1], dp[1][N-1][N-1])) if __name__ == '__main__': main()