#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; long long MOD = 1000000007; struct Point { Point(){}; Point( int a, int b ) { x = a; y = b; } int x; int y; }; int dist( Point p1, Point p2 ) { return abs(p1.x-p2.x) + abs(p1.y-p2.y); } vector V; vector< vector > P(2); int W,H; int dir[4][2] = { {1,0}, {0,1}, {-1,0}, {0,-1} }; bool isOK( int x, int y ) { return x >= 0 && y >= 0 && x < W && y < H; } void func( int a, int x, int y ) { // cout << a << " " << x << " " << y << endl; Point p(x,y); P[a].push_back(p); V[y][x] = '#'; for ( int i = 0; i < 4; i++ ) { int nx = x + dir[i][0]; int ny = y + dir[i][1]; if ( isOK(nx,ny) && V[ny][nx] != '#' ) { func(a,nx,ny); } } } int main() { cin >> W >> H; V.resize(H); for ( int i = 0; i < H; i++ ) { cin >> V[i]; } int a = 0; for ( int y = 0; y < H; y++ ) { for ( int x = 0; x < W; x++ ) { if ( V[y][x] != '#' ) { func(a,x,y); a++; } } } int ans = INT_MAX; for ( int i = 0; i < P[0].size(); i++ ) { for ( int j = 0; j < P[1].size(); j++ ) { ans = min( ans, dist( P[0][i], P[1][j] )-1 ); } } cout << ans << endl; return 0; }