#include #define rep(i,n) for(int i=0; i<(int)(n); i++) using namespace std; using LL = long long; const int Max_N = 510; const LL INF = 1e15; int N, M; int dh[4]={1,0,-1,0}; int dw[4]={0,1,0,-1}; LL c[Max_N][Max_N]; LL dist[Max_N][Max_N]; LL ans=INF; bool visited[Max_N][Max_N]; void dfs(int h, int w, LL max_f){ if(h==N-1 and w==N-1){ ans=min(ans,dist[h][w]-max_f); return; } visited[h][w]=true; rep(i,4){ int nh=h+dh[i], nw=w+dw[i]; if(nh<0 or nh>=N) continue; if(nw<0 or nw>=N) continue; if(visited[nh][nw]) continue; LL nf=dist[h][w]+c[nh][nw]+1; dist[nh][nw]=nf; LL max_nf=max(max_f,c[nh][nw]); dfs(nh,nw,max_nf); } visited[h][w]=false; } int main(){ cin >> N >> M; rep(i,M){ int h, w; LL f; cin >> h >> w >> f; h--; w--; c[h][w]=f; } dfs(0,0,0); cout << ans << endl; return 0; }