#include #include #include #include #include #include #include #include #include // require sort next_permutation count __gcd reverse etc. #include // require abs exit atof atoi #include // require scanf printf #include #include // require accumulate #include // require fabs #include #include #include #include // require setw #include // require stringstream #include // require memset #include // require tolower, toupper #include // require freopen #include // require srand #define rep(i,n) for(int i=0;i<(n);i++) #define ALL(A) A.begin(), A.end() #define INF 1<<10 using namespace std; typedef long long ll; typedef pair P; typedef pair PI; const int dr[4] = {-1, 0, 1, 0 }; const int dc[4] = { 0, 1, 0,-1 }; int W, H; char cave[22][22]; int used[22][22]; void dfs (int r, int c, char ch1, char ch2 ){ // 現在位置 (r, c ) 通過可能文字 ch1 上書き文字 ch2 cave[r][c] = ch2; rep (k, 4 ){ int nr = r + dr[k]; int nc = c + dc[k]; if (nr < 0 || nr >= H || nc < 0 || nc >= W ) continue; if (cave[nr][nc] != ch1 ) continue; dfs (nr, nc, ch1, ch2 ); } // end rep } int bfs (int r, int c, char ch1, char ch2 ){ // 現在位置 (r, c ) 通過可能文字 ch1 探索文字 ch2 memset (used, -1, sizeof (used ) ); used[r][c] = 0; queue que; que.push (PI(P (r, c ), 0 ) ); while (!que.empty() ){ PI curr = que.front(); que.pop(); int cr = curr.first.first; int cc = curr.first.second; int cn = curr.second; used[cr][cc] = cn; rep (k, 4 ){ int nr = cr + dr[k]; int nc = cc + dc[k]; if (nr < 0 || nr >= H || nc < 0 || nc >= W ) continue; if (cave[nr][nc] == ch2 ) return cn; if (cave[nr][nc] != ch1 && cave[nr][nc] != '1' ) continue; if (used[nr][nc] == -1 || used[nr][nc] > used[r][c] + 1 ){ que.push (PI( P (nr, nc ), cn + 1 ) ); } // end if } // end rep } // end while return -1; } void disp_cave (void ){ rep (i, H ){ rep (j, W ){ cerr << cave[i][j]; } // end rep cerr << endl; } // end rep } void disp_used (void ){ cerr << endl; rep (i, H ){ rep (j, W ){ cerr << setw(2) << used[i][j]; } // end rep cerr << endl; } // end rep } int main() { memset (cave, 0, sizeof (cave ) ); ios_base::sync_with_stdio(0); cin >> W >> H; rep (i, H ) rep (j, W ) cin >> cave[i][j]; int cnt = 0; rep (i, H ) rep (j, W ) if (cave[i][j] == '.' ){ dfs (i, j, '.', (char)('1'+cnt) ); cnt++; } // end if // disp_cave (); int res = INF; rep (i, H ) rep (j, W ) if (cave[i][j] == '1' ){ int curr = bfs (i, j, '#', '2' ); res = min (res, curr ); // disp_used (); } // end if cout << res << endl; return 0; }