#include #include #include #include #include #include #include using namespace std; const int dx[4] = {0, 1, 0, -1}; const int dy[4] = {1, 0, -1, 0}; int w, h; bool is_inside(int x, int y) { return (0 <= x && x <= w && 0 <= y && y <= h); } int main() { cin >> w >> h; vector board(h); for (int i = 0; i < h; i++) { cin >> board[i]; } int x, y; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (board[i][j] == '.') { x = j; y = i; break; } } } queue que_start; queue< pair > que_wall; que_start.push(x * 100 + y); que_wall.push(make_pair(x * 100 + y, 0)); board[y][x] = 'S'; int nx, ny; while (!que_start.empty()) { int pos = que_start.front(); que_start.pop(); for (int i = 0; i < 4; i++) { nx = pos / 100 + dx[i]; ny = pos % 100 + dy[i]; if (is_inside(nx, ny) && board[ny][nx] == '.') { board[ny][nx] = 'S'; que_start.push(nx * 100 + ny); que_wall.push(make_pair(nx * 100 + ny, 0)); } } } int ans = -1; while (!que_wall.empty() && ans == -1) { pair pos = que_wall.front(); que_wall.pop(); for (int i = 0; i < 4; i++) { nx = pos.first / 100 + dx[i]; ny = pos.first % 100 + dy[i]; if (is_inside(nx, ny)) { if (board[ny][nx] == '.') { ans = pos.second; break; } else if (board[ny][nx] == '#') { board[ny][nx] = '+'; que_wall.push(make_pair(nx * 100 + ny, pos.second + 1)); } } } } cout << ans << endl; return 0; }