import heapq class Graph(): def __init__(self, N, Type): self._V = N # 頂点の数 self._E = 0 # 辺の数 self.type = Type if Type == "D": # 2次元リスト self.G = [[] for i in range(self._V+1)] elif Type == "W": # 隣接行列 self.G = [[float("inf") for i in range(self._V+1)] for j in range(self._V+1)] elif Type == "B" or Type == "K": # 1次元リスト self.G = [] def E(self): """ 辺数 """ return self._E @property def V(self): """ 頂点数 """ return self._V def add(self, _from, _to, _cost): """ 2頂点と、辺のコストを追加する """ self._E += 1 if self.type == "D": self.G[_from].append((_to, _cost)) elif self.type == "W": self.G[_from][_to] = _cost elif self.type == "B" or self.type == "K": self.G.append((_from, _to, _cost)) def add_both(self, _from, _to, _cost): """ 2頂点と、辺のコストを追加する (無向グラフ) """ self.add(_from, _to, _cost) self.add(_to, _from, _cost) class Dijkstra(Graph): def __init__(self, N): super().__init__(N, "D") self.d = [10**20]*(self._V + 1) self.que = [] heapq.heapify(self.que) def shortest_path(self, s): for i in range(self._V+1): self.d[i] = 10**20 self.d[s] = 0 heapq.heappush(self.que, (0, s)) while self.que: cost, v = heapq.heappop(self.que) if self.d[v] < cost: continue for node, cost in self.G[v]: if self.d[node] > self.d[v] + cost: self.d[node] = self.d[v] + cost heapq.heappush(self.que, (self.d[node], node)) return self.d N, M = map(int, input().split()) dif = [(-1, 0), (1, 0), (0, 1), (0, -1)] cost = [0]*(N**2) G = Dijkstra(N**2) Gs = Dijkstra(N**2) def press(i, j): return N*i + j for i in range(M): h, w, c = map(int, input().split()) h -= 1 w -= 1 cost[press(h, w)] = c inf = 1 << 60 for i in range(N): for j in range(N): now = press(i, j) for dx, dy in dif: if 0 <= dx + i < N and 0 <= dy + j < N: adj = press(dx+i, dy + j) G.add(now, adj, cost[adj] + 1) Gs.add(now,adj, cost[now] + 1) G_s = G.shortest_path(0) Gs_g = Gs.shortest_path(N**2 - 1) ans = inf for i in range(1, N**2 - 1): ans = min(ans, G_s[i] + Gs_g[i] - cost[i]) print(ans)