#include #include using namespace std; int w, h; vector > f, c; int calc_connection(void) { int vx[]={ 1, 0,-1, 0}; int vy[]={ 0,-1, 0, 1}; int x, y, n, i, ret=0; for(y=1;y<=h;y++) { for(x=1;x<=w;x++) { if(f[y][x]==0) continue; c[y][x]=0; n=f[y][x]; for(i=0;i<4;i++) { if(n==f[y+vy[i]][x+vx[i]]) { c[y][x]++; ret=1; } } if(c[y][x]==0) f[y][x]=0; } } return ret; } int remove_connection(int x, int y) { int vx[]={ 1, 0,-1, 0}; int vy[]={ 0,-1, 0, 1}; int i, n, nx, ny; n=f[y][x]; for(;;) { c[y][x]--; if(c[y][x]<=0) { f[y][x]=0; } for(i=0;i<4;i++) { nx=x+vx[i]; ny=y+vy[i]; if(f[ny][nx]>0 && c[ny][nx]<2) { break; } } if(i>=4) break; x=nx; y=ny; } } int solve(void) { int x, y, is_removed=1, ret=0; for(;is_removed;) { ret=calc_connection(); is_removed=0; for(y=1;y<=h;y++) { for(x=1;x<=w;x++) { if(c[y][x]==1 && f[y][x]>0) { remove_connection(x, y); is_removed=1; } } } } return ret; } int main(void) { int i, x, y; while(scanf("%d%d", &w, &h)==2) { f.clear(); f.resize(h+2); for(i=0;i