#include using namespace std; #define rep(i,n) for(int i = 0; i < (n); ++i) #define rrep(i,n) for(int i = (n)-1; i >= 0; --i) #define chmax(a, b) a = max(a, b) #define chmin(a, b) a = min(a, b) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; template std::vector dijkstra(std::vector>>& to, int s=0) { const unsigned long long INF = 1002003004005006007; struct QueElem { int v; unsigned long long c; bool operator<(const QueElem a) const {return c > a.c;} QueElem(int v, unsigned long long c): v(v), c(c) {} }; std::priority_queue q; std::vector dist(to.size(), INF); dist[s] = 0; q.emplace(s, 0); while(!q.empty()) { QueElem qe = q.top(); q.pop(); int u = qe.v; unsigned long long c = qe.c; if (c > dist[u]) continue; for(auto vc: to[u]) { int v = vc.first; unsigned long long nc = c + vc.second; if (nc < dist[v]) { dist[v] = nc; q.emplace(v, nc); } } } return dist; } const int dx[] = {1,0,-1,0}; const int dy[] = {0,1,0,-1}; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; VVI gcost(n, VI(n)); rep(_, m) { int h, w, c; cin >> h >> w >> c; --h, --w; gcost[h][w] = c; } int n2 = n * n; vector>> to(n2 * 2); rep(s, 2) rep(i, n) rep(j, n) { int orig = i * n + j + s * n2; rep(k, 4) { int ni = i + dx[k], nj = j + dy[k]; if (!(0 <= ni && ni < n && 0 <= nj && nj < n)) continue; int dest = ni * n + nj + s * n2; to[orig].emplace_back(dest, 1 + gcost[ni][nj]); if (s == 0) to[orig].emplace_back(dest + n2, 1); } } auto res = dijkstra(to); cout << res.back() << endl; }