#include using namespace std; using ll = long long; template using pq = priority_queue, greater>; int main(){ cin.tie(nullptr); ios_base::sync_with_stdio(false); ll N, M, h, w, x, nh, nw, d, alt; bool f; cin >> N >> M; vector c(N, vector(N)); for (int i=0; i> h >> w >> x; h--; w--; c[h][w] = x; } pq> que; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; vector dist(N, vector(N, vector(2, 1e18))); vector vst(N, vector(N, vector(2, 0))); dist[0][0][0] = 0; que.push({0, 0, 0, 0}); while(!que.empty()){ tie(d, h, w, f) = que.top(); que.pop(); if (vst[h][w][f]) continue; vst[h][w][f] = 1; for (int dir=0; dir<4; dir++){ nh = h + dx[dir]; nw = w + dy[dir]; if (nh < 0 || nh >= N || nw < 0 || nw >= N) continue; alt = dist[h][w][f]+1+c[nh][nw]; if (alt < dist[nh][nw][f]){ dist[nh][nw][f] = alt; que.push({dist[nh][nw][f], nh, nw, f}); } if (f == 0){ alt = dist[h][w][f]+1; if (alt < dist[nh][nw][1]){ dist[nh][nw][1] = alt; que.push({dist[nh][nw][1], nh, nw, 1}); } } } } cout << min(dist[N-1][N-1][0], dist[N-1][N-1][1]) << endl; return 0; }