题解
2023-08-27 16:22:31
发布于:广东
1阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int n, k;
const int MAX_ROWS = 100;
const int MAX_COLS = 10;
vector<vector<char>> board(MAX_ROWS, vector<char>(MAX_COLS));
vector<vector<bool>> visited(MAX_ROWS, vector<bool>(MAX_COLS));
vector<pair<int, int>> component;
int floodfill(int i, int j, char color) {
int cnt = 1;
if (i < 0 || j < 0 || i >= n || j >= MAX_COLS || visited[i][j] ||
board[i][j] != color) {
return 0;
}
visited[i][j] = 1;
component.push_back({i, j});
cnt += (floodfill(i + 1, j, color) + floodfill(i - 1, j, color) +
floodfill(i, j + 1, color) + floodfill(i, j - 1, color));
return cnt;
}
int main() {
cin >> n >> k;
for (int i = n - 1; i >= 0; i--) {
string nums;
cin >> nums;
for (int j = 0; j < MAX_COLS; j++) { board[i][j] = nums[j]; }
}
bool board_changed = true;
while (board_changed) {
board_changed = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < MAX_COLS; j++) {
if (!visited[i][j] && board[i][j] != '0') {
char current_color = board[i][j];
int cnt = floodfill(i, j, current_color);
if (cnt >= k) {
// found a region to destroy
board_changed = true;
for (auto p : component) {
board[p.first][p.second] = '0';
}
}
component.clear();
}
}
}
for (int col = 0; col < MAX_COLS; col++) {
vector<char> column_after_gravity;
for (int row = 0; row < n; row++) {
if (board[row][col] != '0') {
column_after_gravity.push_back(board[row][col]);
}
}
for (int row = 0; row < n; row++) {
if (row < column_after_gravity.size()) {
board[row][col] = column_after_gravity[row];
} else {
board[row][col] = '0';
}
}
}
fill(visited.begin(), visited.end(), vector<bool>(MAX_COLS, false));
}
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < MAX_COLS; j++) { cout << board[i][j]; }
cout << '\n';
}
}
这里空空如也
有帮助,赞一个