## https://yukicoder.me/problems/no/1283 import heapq MAX_INT = 10 ** 18 def main(): N, M = map(int, input().split()) pass_map = [[0] * N for _ in range(N)] for _ in range(M): h, w, c = map(int, input().split()) pass_map[h - 1][w - 1] = c seen = [[[MAX_INT] * N for _ in range(N)] for _ in range(2)] seen[0][0][0] = 0 fix = [[[MAX_INT] * N for _ in range(N)] for _ in range(2)] queue = [] heapq.heappush(queue, (0, 0, 0, 0)) while len(queue) > 0: cost, state, h, w = heapq.heappop(queue) if fix[state][h][w] <= cost: continue fix[state][h][w] = cost for dh, dw in ((0, 1), (1, 0), (0, -1), (-1, 0)): new_h = h + dh new_w = w + dw if 0 <= new_h and new_h < N and 0 <= new_w and new_w < N: # 普通に手数料を払う場合 if fix[state][new_h][new_w] >= MAX_INT: new_cost = cost + 1 + pass_map[new_h][new_w] if seen[state][new_h][new_w] > new_cost: seen[state][new_h][new_w] = new_cost heapq.heappush(queue, (new_cost, state, new_h, new_w)) # 免除を使う場合 if state == 0 and pass_map[new_h][new_w] > 0: if fix[1][new_h][new_w] >= MAX_INT: new_cost = cost + 1 if seen[1][new_h][new_w] > new_cost: seen[1][new_h][new_w] = new_cost heapq.heappush(queue, (new_cost, 1, new_h, new_w)) answer = min(fix[0][N - 1][N - 1], fix[1][N - 1][N - 1]) if answer == float("inf"): print(-1) else: print(answer) if __name__ == "__main__": main()