#include using namespace std; using ll = long long; constexpr char newl = '\n'; constexpr int dh[] = {1, -1, 0, 0}; constexpr int dw[] = {0, 0, 1, -1}; struct State { int at; ll cost; bool used; //int prev; State(int at, ll cost, bool used) : at(at), cost(cost), used(used) {} bool operator>(const State& s) const { return cost > s.cost; } }; struct Edge { int to; ll cost; Edge(int to, ll cost) : to(to), cost(cost) {} }; using Graph = vector< vector >; //隣接リスト const ll INF = 1e15; //const int NONE = -1; //sは始点、mincは最短経路のコスト、prevsは最短経路をたどる際の前の頂点 void dijkstra(int s, const Graph& graph, vector< vector >& minc){ minc.assign(2, vector(graph.size(), INF)); priority_queue, greater > pq; pq.emplace(s, 0, false); minc[false][s] = 0; while(!pq.empty()) { State cur = pq.top(); pq.pop(); if (minc[cur.used][cur.at] < cur.cost) continue; for(const Edge& e : graph[cur.at]) { if (!cur.used) { ll cost = cur.cost + 1; if (minc[true][e.to] > cost) { minc[true][e.to] = cost; pq.emplace(e.to, cost, true); } } ll cost = cur.cost + e.cost; if (minc[cur.used][e.to] <= cost) continue; minc[cur.used][e.to] = cost; pq.emplace(e.to, cost, cur.used); } } } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n, m; cin >> n >> m; vector< vector > memo(n, vector(n, 0)); for (int i = 0; i < m; i++) { int h, w; ll c; cin >> h >> w >> c; --h; --w; memo[h][w] = c; } Graph g(n * n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < 4; k++) { int nh = i + dh[k], nw = j + dw[k]; if (nh < 0 || nh >= n || nw < 0 || nw >= n) continue; g[i * n + j].emplace_back(nh * n + nw, memo[nh][nw] + 1); } } } vector< vector > minc; dijkstra(0, g, minc); int goal = (n - 1) * n + (n - 1); cout << min(minc[0][goal], minc[1][goal]) << newl; return 0; }