#include "bits/stdc++.h" using namespace std; //#include "atcoder/all" //using namespace atcoder; #define int long long #define REP(i, n) for (int i = 0; i < (int)n; ++i) #define RREP(i, n) for (int i = (int)n - 1; i >= 0; --i) #define FOR(i, s, n) for (int i = s; i < (int)n; ++i) #define RFOR(i, s, n) for (int i = (int)n - 1; i >= s; --i) #define ALL(a) a.begin(), a.end() #define IN(a, x, b) (a <= x && x < b) templateistream&operator >>(istream&is,vector&vec){for(T&x:vec)is>>x;return is;} templateinline void out(T t){cout << t << "\n";} templateinline void out(T t,Ts... ts){cout << t << " ";out(ts...);} templateinline bool CHMIN(T&a,T b){if(a > b){a = b;return true;}return false;} templateinline bool CHMAX(T&a,T b){if(a < b){a = b;return true;}return false;} constexpr int INF = 1e18; int dist[505][505][2]; vector>dir = {{1,0},{0,1},{-1,0},{0,-1}}; const int dx[] = {0, 1, 1, 1, 0, -1, -1, -1, 0}; const int dy[] = {1, 1, 0, -1, -1, -1, 0, 1, 1}; signed main(){ int N, M; cin >> N >> M; vector>fee(N, vector(N)); REP(i, M) { int h, w, c; cin >> h >> w >> c; fee[h - 1][w - 1] = c; } REP(i, N) REP(j, N) fee[i][j] += 1; REP(i, 505) REP(j, 505) REP(k, 2) dist[i][j][k] = INF; dist[0][0][0] = 0; using T = tuple; priority_queue, greater> que; que.push({0, 0, 0, 0}); while(que.size()) { auto[cost, i, j, free] = que.top(); que.pop(); if(dist[i][j][free] != cost) continue; for(auto[dx, dy]: dir) { int ni = i + dx; int nj = j + dy; if(!IN(0, ni, N) || !IN(0, nj, N)) continue; if(CHMIN(dist[ni][nj][free], cost + fee[ni][nj])) { que.push({dist[ni][nj][free], ni, nj, free}); } if(free == 0 && CHMIN(dist[ni][nj][1], cost + 1)) { que.push({dist[ni][nj][1], ni, nj, 1}); } } } out(min(dist[N - 1][N - 1][0], dist[N - 1][N - 1][1])); }