#define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include ///////// #define REP(i, x, n) for(int i = x; i < n; i++) #define rep(i,n) REP(i,0,n) #define P(p) std::cout<<(p)<>W>>H; int fi[20][20]; char c; int y=-1,x; rep(h,H)rep(w,W){ cin>>c; if(c=='#'){ fi[h][w] = -1; }else{ fi[h][w] = 0; if(y==-1){ y=h; x=w; } } } queue< pair > qu; qu.push( pair(y,x) ); pair temp; int dy[4] = { 0, 1, 0,-1}; int dx[4] = { 1, 0,-1, 0}; while(!qu.empty()){ temp = qu.front(); qu.pop(); fi[temp.first][temp.second] = 1; for(int i=0;i<4;++i){ if( 0 <= temp.first + dy[i] && temp.first + dy[i] < H && 0 <= temp.second + dx[i] && temp.second + dx[i] < W){ if(fi[temp.first + dy[i]][temp.second + dx[i]] == 0){ qu.push(pair(temp.first + dy[i],temp.second + dx[i])); } } } } //1と0 int ans = -1; int tempans; int tfi[20][20]; rep(h,H)rep(w,W){ if( fi[h][w] == 1){ rep(hh,H)rep(ww,W)tfi[hh][ww] = fi[hh][ww]; queue< pair > quu; quu.push(pair(h,w)); //tfi[h][w] = 0;//最後に-1する while(!quu.empty()){ temp = quu.front(); quu.pop(); for(int i=0;i<4;++i){ if( 0 <= temp.first + dy[i] && temp.first + dy[i] < H && 0 <= temp.second + dx[i] && temp.second + dx[i] < W){ if(tfi[temp.first + dy[i]][temp.second + dx[i]] == -1){ tfi[temp.first + dy[i]][temp.second + dx[i]] = tfi[temp.first][temp.second] + 1; quu.push(pair(temp.first + dy[i],temp.second + dx[i])); }else if(tfi[temp.first + dy[i]][temp.second + dx[i]] == 0){ tempans = tfi[temp.first][temp.second] + 1; if( ans == -1 || ans > tempans){ ans = tempans; } while(!quu.empty())quu.pop(); break; } } } } } } P(ans-2); return 0; }