#include using namespace std; typedef long long ll; using T = tuple; const ll dx[] = {0, 0, 1, -1}; const ll dy[] = {1, -1, 0, 0}; priority_queue, greater>p; ll dp[505][505][2]; ll n, t; const ll nax = 1e9; bool islegal(ll i, ll 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 (ll i = 0; i < t; i++) { ll x, y, val; cin >> x >> y >> val; --x, --y; v[x][y] += val; } for (ll i = 0; i < n; i++) { for (ll j = 0; j < n; j++) { v[i][j] += 1; } } for (ll i = 0; i < 501; i++) { for (ll k = 0; k < 501; k++) { for (ll 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(); ll cur = get<0>(r); ll x = get<1>(r); ll y = get<2>(r); ll state = get<3>(r); if (dp[x][y][state] != cur)continue; for (ll k = 0; k < 4; k++) { ll nx = x + dx[k]; ll 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 (ll i = 0; i < n; i++) { // for (ll 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; }