#include #include #include #include #include #include #include using namespace std; int main() { int W, H, a = 0, ans = INT_MAX; cin >> W >> H; vector C(H); for (string& i : C) cin >> i; queue> b; vector> c(H, vector(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (!c[i][j] && '.' == C[i][j]) { ++a; b.emplace(i, j); c[i][j] = a; while (!b.empty()) { if (!c[b.front().first - 1][b.front().second] && '.' == C[b.front().first - 1][b.front().second]) { b.emplace(b.front().first - 1, b.front().second); c[b.front().first - 1][b.front().second] = a; } if (!c[b.front().first][b.front().second - 1] && '.' == C[b.front().first][b.front().second - 1]) { b.emplace(b.front().first, b.front().second - 1); c[b.front().first][b.front().second - 1] = a; } if (!c[b.front().first][1 + b.front().second] && '.' == C[b.front().first][1 + b.front().second]) { b.emplace(b.front().first, 1 + b.front().second); c[b.front().first][1 + b.front().second] = a; } if (!c[1 + b.front().first][b.front().second] && '.' == C[1 + b.front().first][b.front().second]) { b.emplace(1 + b.front().first, b.front().second); c[1 + b.front().first][b.front().second] = a; } b.pop(); } } } } for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (1 == c[i][j]) { for (int k = 0; k < H; ++k) { for (int l = 0; l < W; ++l) { if (2 == c[k][l]) { b.emplace(i, j); vector> d(H, vector(W, -1)); d[i][j] = 0; while (!b.empty()) { if (H - 1 != b.front().first) { if (-1 == d[1 + b.front().first][b.front().second]) { b.emplace(1 + b.front().first, b.front().second); d[1 + b.front().first][b.front().second] = d[b.front().first][b.front().second]; if ('#' == C[b.front().first][b.front().second]) ++d[1 + b.front().first][b.front().second]; } } if (W - 1 != b.front().second) { if (-1 == d[b.front().first][1 + b.front().second]) { b.emplace(b.front().first, 1 + b.front().second); d[b.front().first][1 + b.front().second] = d[b.front().first][b.front().second]; if ('#' == C[b.front().first][b.front().second]) ++d[b.front().first][1 + b.front().second]; } } if (b.front().first) { if (-1 == d[b.front().first - 1][b.front().second]) { b.emplace(b.front().first - 1, b.front().second); d[b.front().first - 1][b.front().second] = d[b.front().first][b.front().second]; if ('#' == C[b.front().first][b.front().second]) ++d[b.front().first - 1][b.front().second]; } } if (b.front().second) { if (-1 == d[b.front().first][b.front().second - 1]) { b.emplace(b.front().first, b.front().second - 1); d[b.front().first][b.front().second - 1] = d[b.front().first][b.front().second]; if ('#' == C[b.front().first][b.front().second]) ++d[b.front().first][b.front().second - 1]; } } b.pop(); } ans = min(ans, d[k][l]); } } } } } } cout << ans; }