#include #define rep(i,n) for(int i = 0; i < (n); i++) using namespace std; typedef long long ll; int dx[] = {1,0,-1,0}; int dy[] = {0,1,0,-1}; int main(){ cin.tie(0); ios::sync_with_stdio(0); int N,M; cin >> N >> M; vector> A(N, vector (N,0)); rep(i,M){ int h,w,c; cin >> h >> w >> c; h--; w--; A[h][w] = c; } priority_queue, vector>,greater>> Q; vector>> cost(N,vector>(N, vector (2,-1))); Q.push({0,0,0,0}); while(!Q.empty()){ auto [sum,y,x,u] = Q.top(); Q.pop(); if(cost[y][x][u] == -1){ cost[y][x][u] = sum; rep(i,4){ int ny = y + dy[i]; int nx = x + dx[i]; if(ny < 0 || N <= ny || nx < 0 || N <= nx) continue; if(cost[ny][nx][u] == -1){ Q.push({sum+A[ny][nx]+1, ny, nx, u}); } if(u == 0 && cost[ny][nx][1] == -1){ Q.push({sum+1, ny, nx, 1}); } } } } cout << cost[N-1][N-1][1] << '\n'; }