#include #include #include #include #include #include #include #define rep(i,n) for(int i=0; i<(int)(n); i++) using namespace std; using LL = long long; using P = pair; const int Max_N = 500; const LL Max_F = 1e9; const LL INF = 1e18; int dh[4]={1,0,-1,0}; int dw[4]={0,1,0,-1}; struct ver{ int h, w, used; LL fee; ver(int h, int w, LL fee, int used): h(h), w(w), fee(fee), used(used){} bool operator>(const ver& v) const{ if(fee == v.fee) return used > v.used; return fee > v.fee; } }; LL c[Max_N][Max_N]; LL dist[Max_N][Max_N][2]; int main(){ int N, M; cin >> N >> M; assert(2<=N and N<=Max_N); assert(1<=M and M<=N*N-2); map mp; rep(i,M){ int h, w; LL f; cin >> h >> w >> f; assert(1<=h and h<=N); assert(1<=w and w<=N); assert(1<=f and f<=Max_F); assert(h!=1 or w!=1); assert(h!=N or w!=N); h--; w--; assert(mp[P(h,w)]==0); mp[P(h,w)]++; c[h][w]=f; } priority_queue,greater> q; rep(i,N){ rep(j,N){ rep(k,2) dist[i][j][k]=INF; } } dist[0][0][0]=0, dist[0][0][1]=0; ver st(0,0,0,0); q.push(st); while(!q.empty()){ ver v=q.top(); q.pop(); int h=v.h, w=v.w, used=v.used; LL fee=v.fee; if(dist[h][w][used]=N) continue; if(nw<0 or nw>=N) continue; LL nf0=fee+c[nh][nw]+1, nf1=fee+1; if(!used){ if(dist[nh][nw][0]>nf0){ ver next0(nh,nw,nf0,0); q.push(next0); dist[nh][nw][0]=nf0; } if(dist[nh][nw][1]>nf1){ ver next1(nh,nw,nf1,1); q.push(next1); dist[nh][nw][1]=nf1; } } else{ if(dist[nh][nw][1]>nf0){ ver next(nh,nw,nf0,1); q.push(next); dist[nh][nw][1]=nf0; } } } } cout << min(dist[N-1][N-1][0],dist[N-1][N-1][1]) << endl; return 0; }