#include //#include //#pragma GCC optimize("O3") using namespace std; #define reps(i,s,n) for(int i = s; i < n; i++) #define rep(i,n) reps(i,0,n) #define Rreps(i,n,e) for(int i = n - 1; i >= e; --i) #define Rrep(i,n) Rreps(i,n,0) #define ALL(a) a.begin(), a.end() #define fi first #define se second using ll = long long; using vec = vector; using mat = vector; ll N,M,H,W,Q,K,A,B; string S; typedef pair P; const ll INF = (1LL<<60); template bool chmin(T &a, const T &b){ if(a > b) {a = b; return true;} else return false; } template bool chmax(T &a, const T &b){ if(a < b) {a = b; return true;} else return false; } int main(){ cin>>N>>M; mat grid(N, vec(N, 0)); rep(i, M){ int h, w; cin>>h>>w; --h; --w; cin>>grid[h][w]; } vector dist(2, mat(N, vec(N, INF))); dist[0][0][0] = 0; priority_queue, greater<> > pque; pque.emplace(0, (0 * N + 0) * N + 0); vec dh = {-1, 0, 1, 0}, dw = {0, -1, 0, 1}; while(!pque.empty()){ P p = pque.top(); pque.pop(); ll d = p.first, flag = p.se >= N * N, h = (p.se % (N * N)) / N, w = p.se % N; if(dist[flag][h][w] < d) continue; //cout<= 0 && nh < N && nw >= 0 && nw < N){ if(chmin(dist[flag][nh][nw], d + 1 + grid[nh][nw])){ pque.emplace(dist[flag][nh][nw], (flag * N + nh) * N + nw); } if(flag == 0 && grid[nh][nw] && chmin(dist[1][nh][nw], d + 1)){ pque.emplace(dist[1][nh][nw], (N + nh) * N + nw); } } } } cout<