#include using namespace std; vector dy = {1, 0, -1, 0}; vector dx = {0, 1, 0, -1}; int main(){ int N, M; cin >> N >> M; vector> A(N, vector(N, 0)); for (int i = 0; i < M; i++){ int h, w, c; cin >> h >> w >> c; h--; w--; A[h][w] = c; } priority_queue, vector>, greater>> pq; vector>> cost(N, vector>(N, vector(2, -1))); pq.push(make_tuple(0, 0, 0, 0)); while (!pq.empty()){ long long sum = get<0>(pq.top()); int y = get<1>(pq.top()); int x = get<2>(pq.top()); int u = get<3>(pq.top()); pq.pop(); if (cost[y][x][u] == -1){ cost[y][x][u] = sum; for (int i = 0; i < 4; i++){ int y2 = y + dy[i]; int x2 = x + dx[i]; if (0 <= y2 && y2 < N && 0 <= x2 && x2 < N){ if (cost[y2][x2][u] == -1){ pq.push(make_tuple(sum + A[y2][x2] + 1, y2, x2, u)); } if (u == 0 && cost[y2][x2][1] == -1){ pq.push(make_tuple(sum + 1, y2, x2, 1)); } } } } } cout << cost[N - 1][N - 1][1] << endl; }