#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <cmath>
#include <climits>
#include <string>
#include <bitset>
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
const int MOD = 998244353;
const int MOD1 = 1e9 + 7;
const double EPS = 1e-8;
void fastOI(){
ios::sync_with_stdio(false);
cin.tie(0);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
}
int main() {
fastOI();
int R, C;
cin >> R >> C;
vector<string> grid(R);
for (int i = 0; i < R; i++) {
cin >> grid[i];
}
vector<string> future = grid;
// 检查每个陆地格子
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (grid[r][c] == 'X') {
int sea_count = 0;
// 检查上方向
if (r == 0 || grid[r-1][c] == '.') sea_count++;
// 检查下方向
if (r == R-1 || grid[r+1][c] == '.') sea_count++;
// 检查左方向
if (c == 0 || grid[r][c-1] == '.') sea_count++;
// 检查右方向
if (c == C-1 || grid[r][c+1] == '.') sea_count++;
// 如果三面或四面是海,则被淹没
if (sea_count >= 3) {
future[r][c] = '.';
}
}
}
}
// 找到包含所有剩余陆地的矩形边界
int min_row = R, max_row = -1;
int min_col = C, max_col = -1;
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
if (future[r][c] == 'X') {
min_row = min(min_row, r);
max_row = max(max_row, r);
min_col = min(min_col, c);
max_col = max(max_col, c);
}
}
}
// 输出最小区域
for (int r = min_row; r <= max_row; r++) {
for (int c = min_col; c <= max_col; c++) {
cout << future[r][c];
}
cout << endl;
}
return 0;
}题解:SP20985 UCBINTG - Archipelago
这是 2025年11月10日 存档的第 1 版,不是当前版本。查看当前版本