AtCoder题解|ABC 107B Grid Compression
题目信息 📚
【题目描述】
There is a grid of squares with $H$ horizontal rows and $W$ vertical columns. The square at the $i$-th row from the top and the $j$-th column from the left is represented as $(i, j)$. Each square is either black or white. The color of the square is given as an $H$-by-$W$ matrix $(a_{i,j})$. If $a_{i,j}$ is .
, the square $(i, j)$ is white; if $a_{i,j}$ is #
, the square $(i, j)$ is black.
Snuke is compressing this grid. He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:
- Operation: Choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.
It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation. Find the final state of the grid.
【输入】
The input is given from Standard Input in the following format:
$H$ $W$
$a_{1,1}$ $\dots$ $a_{1,W}$
$\vdots$
$a_{H,1}$ $\dots$ $a_{H,W}$
【输出】
Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.
【数据范围】
- $1 \leq H, W \leq 100$
- $a_{i,j}$ is
.
or#
. - There is at least one black square in the whole grid.
【输入样例1】
4 4
##.#
....
##.#
.#.#
【输出样例1】
###
###
.##
The second row and the third column in the original grid will be removed.
【输入样例2】
3 3
#..
.#.
..#
【输出样例2】
#..
.#.
..#
As there is no row or column that consists only of white squares, no operation will be performed.
【输入样例3】
4 5
.....
.....
..#..
.....
【输出样例3】
#
【输入样例4】
7 6
......
....#.
.#....
..#...
..#...
......
.#..#.
【输出样例4】
..#
#..
.#.
.#.
#.#
【题目来源】
https://atcoder.jp/contests/abc107/tasks/abc107_b
题目解析 🍉
【题目分析】
模拟 + 打标记即可。
【C++代码】
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 110;
string g[N];
bool row[N], col[N];
int h, w;
int main() {
ios::sync_with_stdio(false); //cin读入优化
cin.tie(0);
// 读入数据
cin >> h >> w;
for (int i = 0; i < h; i++) cin >> g[i];
// 行判断
for (int i = 0; i < h; i++) {
row[i] = true;
for (int j = 0; j < w; j++) {
if (g[i][j] == '#') {
row[i] = false;
break;
}
}
}
// 列判断
for (int i = 0; i < w; i++) {
col[i] = true;
for (int j = 0; j < h; j++) {
if (g[j][i] == '#') {
col[i] = false;
break;
}
}
}
// 根据判断数组输出答案
for (int i = 0; i < h; i++) {
if (row[i]) continue;
else {
for (int j = 0; j < w; j++) {
if (!col[j]) cout << g[i][j];
}
cout << endl;
}
}
return 0;
}