学习C++从娃娃抓起!记录下洛谷C++学习和备考过程中的题目,记录每一个瞬间。
附上汇总贴:洛谷刷题C++语言 | 汇总_热爱编程的通信人的博客-CSDN博客
【题目描述】
由数字 0 组成的方阵中,有一任意形状闭合圈,闭合圈由数字 1 构成,围圈时只走上下左右 4 个方向。现要求把闭合圈内的所有空间都填写成 2。例如:6×6 的方阵(n=6),涂色前和涂色后的方阵如下:
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
【输入】
每组测试数据第一行一个整数 n(1≤n≤30)。
接下来 n 行,由 0 和 1 组成的 n×n 的方阵。
方阵内只有一个闭合圈,圈内至少有一个 0。
【输出】
已经填好数字 2 的完整方阵。
【输入样例】
6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
【输出样例】
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
【代码详解】
#include <bits/stdc++.h>
using namespace std;
int n, tmp, dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int a[35][35]={0}, vis[35][35]={0};
struct node {
int x, y;
};
int main()
{
cin >> n;
for (int i=1; i<=n; i++) {
for (int j=1; j<=n; j++) {
cin >> tmp;
if (tmp==1) a[i][j] = 1;
}
}
queue<node> q;
node tp = {0, 0};
q.push(tp);
vis[0][0]=1;
while (!q.empty()) {
node tp = q.front();
q.pop();
for (int i=0; i<4; i++) {
int xx = tp.x + dx[i];
int yy = tp.y + dy[i];
if (xx<0 || xx>n+1 || yy<0 || yy>n+1) continue;
if (a[xx][yy]==0 && vis[xx][yy]==0) {
vis[xx][yy] = 1;
node t = {xx,yy};
q.push(t);
}
}
}
for (int i=1; i<=n; i++) {
for (int j=1; j<=n; j++) {
if (a[i][j]==0 and vis[i][j]==0) {
cout << 2 << " ";
} else if (a[i][j]==1) {
cout << 1 << " ";
} else {
cout << 0 << " ";
}
}
cout << endl;
}
return 0;
}
【运行结果】
6
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1