#include using namespace std; typedef long long ll; using T = tuple; const int dx[] = {0, 0, 1, -1}; const int dy[] = {1, -1, 0, 0}; priority_queue, greater>p; int dp[505][505][2]; int n, t; const int nax = 1e9; bool islegal(int i, int j) { return (i >= 0 && i < n && j >= 0 && j < n); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> t; vector>v(n, vector(n, 0)); for (int i = 0; i < t; i++) { int x, y, val; cin >> x >> y >> val; --x, --y; v[x][y] += val; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { v[i][j] += 1; } } for (int i = 0; i < 501; i++) { for (int k = 0; k < 501; k++) { for (int q = 0; q < 2; q++) { dp[i][k][q] = nax; } } } dp[0][0][0] = 0; p.push({0, 0, 0, 0}); while (!p.empty()) { T r = p.top(); p.pop(); int cur = get<0>(r); int x = get<1>(r); int y = get<2>(r); int state = get<3>(r); if (dp[x][y][state] != cur)continue; for (int k = 0; k < 4; k++) { int nx = x + dx[k]; int ny = y + dy[k]; //cout << nx << " " << ny << endl; if (islegal(nx, ny)) { if (dp[nx][ny][state] > cur + v[nx][ny]) { dp[nx][ny][state] = cur + v[nx][ny]; p.push({dp[nx][ny][state], nx, ny, state}); } if (state == 0) { if (dp[nx][ny][1] > cur + 1) { dp[nx][ny][1] = cur + 1; p.push({dp[nx][ny][1], nx, ny, 1}); } } } } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < n; j++) { // cout << dp[i][j][0] << " " << dp[i][j][1] << endl; // } // } cout << min(dp[n - 1][n - 1][1], dp[n - 1][n - 1][0]) << endl; }