题解(带批注):
2025-11-29 11:11:10
发布于:上海
3阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <queue>
#include <set>
#include <iomanip>
#include <string>
using i64 = long long;
constexpr int dirs[][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int main() {
stdiossync_with_stdio(false);
std::cin.tie(nullptr);
int n, m;
std::cin >> n >> m;
std::vector<std::string> grid(n);
for (auto &row : grid)
std::cin >> row;
std::vector<std::vector<int>> color(n, std::vector<int>(m, 0));
int k = 0;
// BFS标记蓝色连通分量
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] != 'B' || color[i][j]) continue;
std::queue<std::pair<int, int>> q;
q.emplace(i, j);
color[i][j] = ++k;
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
for (auto &[dr, dc] : dirs) {
int nr = r + dr, nc = c + dc;
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
if (grid[nr][nc] != 'B' || color[nr][nc]) continue;
color[nr][nc] = k;
q.emplace(nr, nc);
}
}
}
}
i64 numerator = 0, denominator = 0;
// 统计白色格子周围的蓝色分量
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] != 'W') continue;
std::set<int> adjacentColors;
for (auto &[dr, dc] : dirs) {
int nr = i + dr, nc = j + dc;
if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue;
if (grid[nr][nc] == 'B') {
adjacentColors.insert(color[nr][nc]);
}
}
numerator += k - adjacentColors.size() + 1;
denominator += 1;
}
}
// 精确输出,避免格式错误
if (denominator == 0) {
std::cout << "0.000000000000\n";
} else {
double result = static_cast<double>(numerator) / denominator;
std::cout << std::fixed << std::setprecision(12) << result << "\n";
}
return 0;
}
这里空空如也







有帮助,赞一个