#include using namespace std; long long int dist[501][501][2]; int dy[4] = {-1,0,1,0}; int dx[4] = {0,1,0,-1}; int n,m,h,w,c; long long int cost[501][501]; int main(void) { cin.tie(0); ios::sync_with_stdio(false); cin >> n >> m; for(int i=0;i> h >> w >> c; cost[h][w] = c; } priority_queue ,int>>> pque; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { dist[i][j][0] = 1e18; dist[i][j][1] = 1e18; } } dist[1][1][0] = 0; pque.push(make_pair(0,make_pair(make_pair(1,1),0))); while(!pque.empty()) { int y = pque.top().second.first.first; int x = pque.top().second.first.second; int c = pque.top().second.second; if(dist[y][x][c] < -pque.top().first) { pque.pop(); continue; } pque.pop(); for(int k=0;k<4;k++) { int ny = y + dy[k]; int nx = x + dx[k]; if(ny<=0 || ny>n || nx<=0 || nx>n) continue; if(c==0) { if(dist[ny][nx][1] > dist[y][x][c] + 1) { dist[ny][nx][1] = dist[y][x][c] + 1; pque.push(make_pair(-dist[ny][nx][1],make_pair(make_pair(ny,nx),1))); } } if(dist[ny][nx][c] > dist[y][x][c] + cost[ny][nx] + 1) { dist[ny][nx][c] = dist[y][x][c] + cost[ny][nx] + 1; pque.push(make_pair(-dist[ny][nx][c],make_pair(make_pair(ny,nx),c))); } } } long long int res = dist[n][n][0]; res = min(res,dist[n][n][1]); cout << res << '\n'; return 0; }