/* -*- coding: utf-8 -*- * * 2328.cc: No.2328 Build Walls - yukicoder */ #include #include #include #include using namespace std; /* constant */ const int MAX_H = 800; const int MAX_W = 800; const int MAX_N = MAX_H * MAX_W + 2; const int INF = 1 << 30; const int dxs[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; const int dys[] = { 0, -1, -1, -1, 0, 1, 1, 1 }; /* typedef */ typedef pair pii; typedef vector vpii; /* global variables */ int as[MAX_H][MAX_W], ds[MAX_N]; vpii nbrs[MAX_N]; /* subroutines */ /* main */ int main() { int h, w; scanf("%d%d", &h, &w); h -= 2; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) scanf("%d", as[i] + j); int st = h * w, gl = st + 1, n = gl + 1; for (int y = 0, u = 0; y < h; y++) for (int x = 0; x < w; x++, u++) if (as[y][x] >= 0) for (int di = 0; di < 8; di++) { int vy = y + dys[di], vx = x + dxs[di], v = vy * w + vx; if (vy >= 0 && vy < h && vx >= 0 && vx < w && as[vy][vx] >= 0) nbrs[u].push_back(pii(v, as[vy][vx])); } for (int y = 0; y < h; y++) { if (as[y][0] >= 0) nbrs[st].push_back(pii(y * w, as[y][0])); if (as[y][w - 1] >= 0) nbrs[y * w + (w - 1)].push_back(pii(gl, 0)); } fill(ds, ds + n, INF); ds[st] = 0; priority_queue q; q.push(pii(0, st)); while (! q.empty()) { auto ue = q.top(); q.pop(); int ud = -ue.first, u = ue.second; if (ds[u] != ud) continue; if (u == gl) break; for (auto &vw: nbrs[u]) { int v = vw.first, vd = ud + vw.second; if (ds[v] > vd) { ds[v] = vd; q.push(pii(-vd, v)); } } } printf("%d\n", (ds[gl] < INF) ? ds[gl] : -1); return 0; }