#pragma GCC optimize("O3") #include #define ll long long #define rep(i,n) for(ll i=0;i<(n);i++) #define pll pair #define pii pair #define pq priority_queue #define pb push_back #define eb emplace_back #define fi first #define se second #define endl '\n' #define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); #define lb(c,x) distance(c.begin(),lower_bound(all(c),x)) #define ub(c,x) distance(c.begin(),upper_bound(all(c),x)) using namespace std; inline int topbit(unsigned long long x){ return x?63-__builtin_clzll(x):-1; } inline int popcount(unsigned long long x){ return __builtin_popcountll(x); } inline int parity(unsigned long long x){//popcount%2 return __builtin_parity(x); } template inline bool chmax(T& a,T b){if(a inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;} const ll INF=1e18; const ll white=0; //未探索 const ll gray=1; //探索中 const ll black=2; //探索済み vector g[500005]; ll v,r; vector d; void dijkstra(){ priority_queue PQ; vector color(v); rep(i,v){ d[i]=INF; color[i]=white; } d[r]=0; PQ.push(make_pair(0,r)); color[r]=gray; while(!PQ.empty()){ pll f=PQ.top(); PQ.pop(); ll u=f.second; color[u]=black; if(d[u]d[u]+g[u][j].second){ d[v]=d[u]+g[u][j].second; PQ.push(make_pair(d[v]*(-1),v)); color[v]=gray; } } } } ll dx[4]={-1,1,0,0}; ll dy[4]={0,0,-1,1}; int main(){ ll n,m; cin >> n >> m; vector h(m),w(m),c(m); map e; rep(i,m){ cin >> h[i] >> w[i] >> c[i]; h[i]--; w[i]--; e[make_pair(h[i],w[i])]=c[i]; } v=2*n*n; d=vector(v,INF); rep(i,n){ rep(j,n){ ll now=i*n+j; if(!e.count({i,j})){ rep(k,4){ ll nx=i+dx[k]; ll ny=j+dy[k]; ll from=nx*n+ny; if(0<=nx && nx<=n-1 && 0<=ny && ny<=n-1){ g[from].push_back({now,1LL}); g[from+n*n].push_back({now+n*n,1LL}); } } } else{ ll cost=e[{i,j}]; rep(k,4){ ll nx=i+dx[k]; ll ny=j+dy[k]; ll from=nx*n+ny; if(0<=nx && nx<=n-1 && 0<=ny && ny<=n-1){ g[from].push_back({now,cost+1}); g[from+n*n].push_back({now+n*n,cost+1}); g[from].push_back({now+n*n,1}); } } } } } dijkstra(); ll ans=INF; ans=min(d[n*n-1],d[2*n*n-1]); cout << ans << endl; return 0; }