B - Crop 解説 by en_translator
While one may naively implement what is described in the problem statement, there are several ideas that simplify the implementation.
Implementation 1
- Considering the minimum rectangle containing all black pixels, and printing that range
may be a good idea. This can be implemented as follows.
Sample code (Python)
H, W = map(int, input().split())
C = [input() for _ in range(H)]
u, d = H, -1
l, r = W, -1
for i in range(H):
for j in range(W):
if C[i][j] == "#":
u, d = min(u, i), max(d, i)
l, r = min(l, j), max(r, j)
for i in range(u, d + 1):
print(C[i][l:r + 1])
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int H, W;
cin >> H >> W;
vector<string> C(H);
for (int i = 0; i < H; i++) cin >> C[i];
int u = H, d = -1;
int l = W, r = -1;
for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) {
if (C[i][j] == '#') {
u = min(u, i); d = max(d, i);
l = min(l, j); r = max(r, j);
}
}
for (int i = u; i <= d; i++) {
for (int j = l; j <= r; j++) {
cout << C[i][j];
}
cout << endl;
}
return 0;
}
Implementation 2
We actually implement removals, but the problem is that the columns and rows to remove are on different sides. Using the property that the order of removal does not matter, one may take the following approach:
- Repeat the following operation four times: rotate the grid by \(90\) degrees, and remove the topmost row until it is not removable anymore.
Rotation of a grid is occasionally used, so some contestants may have a pre-written code snippet.
Sample code (Python)
def rotate(a): return ["".join(r) for r in zip(*a[::-1])]
H, W = map(int, input().split())
C = [input() for _ in range(H)]
for _ in range(4):
while not "#" in C[0]:
C = C[1:]
C = rotate(C)
print(*C, sep = "\n")
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
vector<string> rotate(vector<string> a) {
int h = a.size(), w = a[0].size();
vector<string> res(w, string(h, '.'));
for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) {
res[j][h - 1 - i] = a[i][j];
}
return res;
}
int main() {
int H, W;
cin >> H >> W;
vector<string> C(H);
for (int i = 0; i < H; i++) cin >> C[i];
for (int t = 0; t < 4; t++) {
while (true) {
int ok = 1;
for (int j = 0; j < C[0].size(); j++) ok &= C[0][j] == '.';
if (!ok) break;
C.erase(begin(C));
}
C = rotate(C);
}
for(auto c : C) cout << c << endl;
return 0;
}
投稿日時:
最終更新: