#include using namespace std; #define int long long #define REP(i,m,n) for(int i=(m);i<(n);i++) #define rep(i,n) REP(i,0,n) #define pb push_back #define all(a) a.begin(),a.end() #define rall(c) (c).rbegin(),(c).rend() #define mp make_pair #define endl '\n' #define vec vector #define mat vector > #define fi first #define se second typedef long long ll; typedef unsigned long long ull; typedef pair pll; typedef long double ld; typedef complex comp; const ll INF=1e9+7; const ll inf=INF*INF; const ll MOD=1e9+7; const ll mod=MOD; const int MAX=1000010; const double PI=acos(-1.0); //dijkstra(O(ElogV)) //0-indexed void dijkstra(ll n,ll s,vector >&G,vector &d){ priority_queue,greater >pq; rep(i,n){ d[i]=inf; } d[s]=0; pq.push(mp(0,s)); while(!pq.empty()){ pll k=pq.top();pq.pop(); ll v=k.second; if(d[v]d[v]+e.second){ d[e.first]=d[v]+e.second; pq.push(mp(d[e.first],e.first)); } } } } ll dx[]={0,1,0,-1}; ll dy[]={1,0,-1,0}; signed main(){ ll n,m;cin>>n>>m; vector >c(n,vector(n)); rep(i,m){ ll h,w;cin>>h>>w; h--;w--; cin>>c[h][w]; } vector >G(n*n); vector >G2(n*n); vectord(n*n); vectord2(n*n); rep(i,n){ rep(j,n){ ll now=i*n+j; rep(l,4){ ll nx=i+dx[l],ny=j+dy[l]; if(nx<0||nx>=n||ny<0||ny>=n)continue; ll cost=1+c[nx][ny]; ll to=nx*n+ny; G[now].pb(mp(to,cost)); G2[to].pb(mp(now,cost)); } } } dijkstra(n*n,0,G,d); dijkstra(n*n,n*n-1,G2,d2); ll ans=inf; REP(i,1,n*n-1){ ll h=i/n; ll w=i%n; ll dd=d[i]+d2[i]-c[h][w]; if(c[h][w]==0)dd--; ans=min(d[i]+d2[i]-c[h][w],ans); } cout<