#include #define rep(i, n) for(int i = 0; i < (n); ++i) using namespace std; using Tup = tuple; const int dy[4] = {0, 1, 0, -1}; const int dx[4] = {1, 0, -1, 0}; const long long INF = 1e18; int main() { int n, m; cin >> n >> m; vector cost(n, vector(n)); for(int i = 0; i < m; ++i) { int h, w, c; cin >> h >> w >> c; h--, w--; cost[h][w] = c; } priority_queue, greater> que; vector dist(n, vector(n, vector(2, INF))); auto push = [&](long long c, int y, int x, int t) { if(dist[y][x][t] <= c) return; que.emplace(c, y, x, t); dist[y][x][t] = c; }; push(0, 0, 0, 0); while(!que.empty()) { auto[c, y, x, t] = que.top(); que.pop(); for(int i = 0; i < 4; ++i) { int ny = y + dy[i], nx = x + dx[i]; if(ny < 0 || nx < 0 || ny >= n || nx >= n) continue; if(t == 0) push(dist[y][x][t] + 1, ny, nx, 1); push(dist[y][x][t] + cost[ny][nx] + 1, ny, nx, t); } } cout << dist[n - 1][n - 1][1] << '\n'; return 0; }