#include #include using namespace std; struct State { int row, col, times; }; const int kMAX_W = 30; const int kMAX_H = 30; int W, H; string C[kMAX_H]; bool used[kMAX_H][kMAX_W]; bool is_start[kMAX_H][kMAX_W]; int dr[4] = {1, 0, -1, 0}, dc[4] = {0, 1, 0, -1}; // 一つ目の空洞部分を調べる void DFS(int r, int c, queue& que) { used[r][c] = true; is_start[r][c] = true; que.push((State){r, c, 0}); for (int i = 0; i < 4; i++) { int nr = r + dr[i], nc = c + dc[i]; if (0 <= nr && nr < H && 0 <= nc && nc < W && !used[nr][nc] && C[nr][nc] == '.') { DFS(nr, nc, que); } } } void Solve() { queue que; for (int r = 0; r < H; r++) { bool find_cave = false; for (int c = 0; c < W; c++) { if (C[r][c] == '.') { DFS(r, c, que); find_cave = true; break; } } if (find_cave) break; } while (!que.empty()) { State s = que.front(); que.pop(); if (C[s.row][s.col] == '.' && !is_start[s.row][s.col]) { cout << s.times << endl; return; } for (int i = 0; i < 4; i++) { int nr = s.row + dr[i], nc = s.col + dc[i]; if (0 <= nr && nr < H && 0 <= nc && nc < W && !used[nr][nc]) { int times = s.times + (C[nr][nc] == '#' ? 1 : 0); used[nr][nc] = true; que.push((State){nr, nc, times}); } } } } int main() { cin >> W >> H; for (int i = 0; i < H; i++) { cin >> C[i]; } Solve(); return 0; }