/* -*- coding: utf-8 -*- * * 2731.cc: No.2731 Two Colors - yukicoder */ #include #include #include #include using namespace std; /* constant */ const int MAX_H = 1000; const int MAX_W = 1000; const int MAX_HW = MAX_H * MAX_W; const int dxs[] = { 1, 0, -1, 0 }, dys[] = { 0, -1, 0, 1 }; /* typedef */ typedef pair pii; typedef set spii; /* global variables */ int as[MAX_HW], cs[MAX_HW]; /* subroutines */ void nbrs(int u, int h, int w, spii &b) { int uy = u / w, ux = u % w; for (int di = 0; di < 4; di++) { int vy = uy + dys[di], vx = ux + dxs[di], v = vy * w + vx; if (vy >= 0 && vy < h && vx >= 0 && vx < w && cs[v] < 0) b.insert({as[v], v}); } } /* main */ int main() { int h, w; scanf("%d%d", &h, &w); int hw = h * w; for (int i = 0; i < hw; i++) scanf("%d", as + i); fill(cs, cs + hw, -1); spii bs[2]; cs[0] = 0, nbrs(0, h, w, bs[0]); cs[hw - 1] = 1, nbrs(hw - 1, h, w, bs[1]); int i = 0; for (;;) { int p = (i & 1), q = p ^ 1; spii &bp = bs[p], &bq = bs[q]; if (bp.empty()) break; i++; auto sit = bp.begin(); int u = sit->second; cs[u] = p; //printf(" i=%d: %d,%d\n", i, u / w, u % w); if (bq.find(*sit) != bq.end()) break; bp.erase(sit); nbrs(u, h, w, bp); } printf("%d\n", i); return 0; }