/* -*- coding: utf-8 -*- * * 460.cc: No.460 裏表ちわーわ - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_H = 8; const int MAX_W = 8; const int MAX_HW = MAX_H * MAX_W; 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 unsigned long long ull; typedef pair puli; typedef map muli; /* global variables */ int h, w, hw; ull msks[MAX_HW]; muli dists; /* subroutines */ inline int xy2p(int x, int y) { return y * w + x; } /* main */ int main() { cin >> h >> w; hw = h * w; ull gl = 0, bi = 1; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++, bi <<= 1) { int a; cin >> a; if (a) gl |= bi; } for (int y = 0, p = 0; y < h; y++) for (int x = 0; x < w; x++, p++) { msks[p] = (1ULL << p); for (int di = 0; di < 8; di++) { int x0 = x + dxs[di], y0 = y + dys[di]; if (x0 >= 0 && x0 < w && y0 >= 0 && y0 < h) msks[p] |= (1ULL << xy2p(x0, y0)); } } queue q; dists[0] = 1; q.push(puli(0, 1)); dists[gl] = -1; q.push(puli(gl, -1)); while (! q.empty()) { puli u = q.front(); q.pop(); ull &ui = u.first; int &ud = u.second, vd = (ud >= 0) ? ud + 1 : ud - 1; for (int i = 0; i < hw; i++) { ull vi = ui ^ msks[i]; muli::iterator mit = dists.find(vi); if (mit == dists.end()) { dists[vi] = vd; q.push(puli(vi, vd)); } else if ((vd >= 0 && mit->second < 0) || (vd < 0 && mit->second >= 0)) { int d = abs(vd - mit->second) - 2; printf("%d\n", d); return 0; } } } puts("Impossible"); return 0; }