#include using namespace std; #define LOG(...) fprintf(stderr,__VA_ARGS__) //#define LOG(...) #define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);++i) #define REP(i,n) for(int i=0;i<(int)(n);++i) #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(),(a).rend() #define EXIST(s,e) ((s).find(e)!=(s).end()) #define SORT(c) sort(ALL(c)) #define RSORT(c) sort(RALL(c)) typedef long long ll; typedef unsigned long long ull; typedef vector vb; typedef vector vi; typedef vector vll; typedef vector vvb; typedef vector vvi; typedef vector vvll; typedef pair pii; typedef pair pll; struct P { int x, y, step; }; const int dx[] = {-1,0,1,0}, dy[] = {0,1,0,-1}; int w, h; char cave[20][20]; void dfs_fill(int x, int y, int c) { cave[y][x] = c; REP(i, 4) { int sx = x + dx[i]; int sy = y + dy[i]; if (0 <= sx && sx < w && 0 <= sy && sy < h) { if (cave[sy][sx] == '.') { dfs_fill(sx, sy, c); } } } } int main() { cin >> w >> h; fill_n((char *)cave, 20*20, '#'); REP(y, h) REP(x, w) cin >> cave[y][x]; char c = 'A'; REP(y, h) { REP(x, w) { if (cave[y][x] == '.') { dfs_fill(x, y, c); c = 'B'; } } } queue

que; REP(y, h) { REP(x, w) { if (cave[y][x] == 'A') { que.push({x, y, 0}); } } } while (!que.empty()) { P p = que.front(); que.pop(); REP(i, 4) { int sx = p.x + dx[i]; int sy = p.y + dy[i]; if (0 <= sx && sx < w && 0 <= sy && sy < h) { if (cave[sy][sx] == '#') { cave[sy][sx] = 'A'; que.push({sx, sy, p.step+1}); } else if (cave[sy][sx] == 'B') { cout << p.step << endl; return 0; } } } } }