#include "bits/stdc++.h" using namespace std; using ll = long long; using P = pair>; ll INF = (1LL << 60); int v, e; vector>edge[1000010]; vector> dijkstra(int s) { priority_queue, greater

>pq; vector>dist(v, vector(2, INF)); dist[s][0] = 0; pq.push({ dist[s][0],{s, 0} }); while (!pq.empty()) { P p = pq.top(); pq.pop(); ll d = p.first, from = p.second.first; ll tmp = p.second.second; if (dist[from][tmp] < d)continue; for (auto nv : edge[from]) { int to = nv.first; ll cost = nv.second; if (dist[from][tmp] + cost < dist[to][tmp]) { dist[to][tmp] = dist[from][tmp] + cost; pq.push({ dist[to][tmp],{to, tmp} }); } if (tmp == 0 && cost > 1) { if (dist[from][tmp] + 1 < dist[to][1]) { dist[to][1] = dist[from][tmp] + 1; pq.push({ dist[to][1],{to, 1} }); } } } } return dist; } ll cost[510][510]; int main() { cin >> v >> e; for (int i = 0; i < 510; i++) { for (int j = 0; j < 510; j++) { cost[i][j] = 1; } } for (int i = 0; i < e; i++) { ll h, w, c; cin >> h >> w >> c; cost[h - 1][w - 1] += c; } for (int i = 0; i < v; i++) { for (int j = 0; j < v; j++) { if (i + 1 < v) { edge[i*v + j].push_back({ (i + 1)*v + j, cost[i + 1][j] }); edge[(i + 1)*v + j].push_back({ i*v + j, cost[i][j] }); } if (j + 1 < v) { edge[i*v + j].push_back({ i*v + j + 1, cost[i][j + 1] }); edge[i*v + (j + 1)].push_back({ i*v + j, cost[i][j] }); } } } v *= v; vector>dist = dijkstra(0); cout << min(dist[v - 1][0], dist[v - 1][1]) << endl; }