#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 INF=1e10+100; const ll white=0; //未探索 const ll gray=1; //探索中 const ll black=2; //探索済み vector m[1000005]; ll v,r; ll dx[4]={-1,1,0,0}; ll dy[4]={0,0,-1,1}; 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]+m[u][j].second){ d[v]=d[u]+m[u][j].second; PQ.push(make_pair(d[v]*(-1),v)); color[v]=gray; } } } } int main(){ ll n,M; cin >> n >> M; vector h(M),w(M),c(M); d=vector(n*n,INF); rep(i,n){ rep(j,n){ ll now=i*n+j; rep(k,4){ ll nx=i+dx[k]; ll ny=j+dy[k]; if(0<=nx && nx<=n-1 && 0<=ny && ny<=n-1){ ll val=nx*n+ny; m[now].push_back({val,1LL}); m[val].push_back({now,1LL}); } } } } vector edge(M); rep(i,M){ cin >> h[i] >> w[i] >> c[i]; h[i]--; w[i]--; ll now=h[i]*n+w[i]; rep(k,4){ ll nx=h[i]+dx[k]; ll ny=w[i]+dy[k]; ll val=nx*n+ny; if(0<=nx && nx<=n-1 && 0<=ny && ny<=n-1){ for(auto &x:m[val]){ if(x.fi==now){ x.se=c[i]+1; } } } } } v=n*n; r=0; ll ans=INF; rep(i,M){ ll now=h[i]*n+w[i]; rep(k,4){ ll nx=h[i]+dx[k]; ll ny=w[i]+dy[k]; if(0<=nx && nx<=n-1 && 0<=ny && ny<=n-1){ ll val=nx*n+ny; for(auto &x:m[val]){ if(x.fi==now){ x.se=1; } } } } dijkstra(); ans=min(ans,d[n*n-1]); rep(k,4){ ll nx=h[i]+dx[k]; ll ny=w[i]+dy[k]; if(0<=nx && nx<=n-1 && 0<=ny && ny<=n-1){ ll val=nx*n+ny; for(auto &x:m[val]){ if(x.fi==now){ x.se=c[i]+1; } } } } d=vector(n*n,INF); } cout << ans << endl; return 0; }