#include using namespace std; using ll = long long; //経路復元なしDijkstra法 template vector dijkstra( const vector>>& Hen, int start = 0){ T INF = numeric_limits::max(); int N = Hen.size(); vector dist(N, INF); dist[start] = 0; priority_queue, vector>, greater>> que; que.push({0, start}); while(que.size()) { int ver = que.top().second; T cost = que.top().first; que.pop(); if(cost != dist[ver])continue; for(auto i : Hen[ver]) { if(dist[i.first] > cost + i.second) { dist[i.first] = cost + i.second; que.push({dist[i.first], i.first}); } } } return dist; } vector> dir4(int x, int y) {return {{x - 1, y}, {x, y - 1}, {x + 1, y}, {x, y + 1}};}; int main() { int N, M; cin >> N >> M; vector> grid(N, vector(N, 1)); for(int i = 0; i < M; i++) { int h, w, c; cin >> h >> w >> c; grid[h - 1][w - 1] += c; } int K = N * N; vector>> hen(2 * N * N); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { int cur = i * N + j; for(auto [ny, nx] : dir4(i, j)) { if(ny < 0 || nx < 0 || ny >= N || nx >= N)continue; int nxt = ny * N + nx; hen[cur].push_back({nxt, grid[ny][nx]}); hen[cur + K].push_back({nxt + K, grid[ny][nx]}); hen[cur].push_back({nxt + K, 1}); } } } vector dist = dijkstra(hen); cout << dist[2 * K - 1] << endl; }