案例输入
3
4 5
1 0 0 0 1
1 0 1 0 1
1 0 1 0 1
1 0 0 0 1
5 6
1 1 1 1 1 1
1 0 1 0 1 1
1 0 1 0 1 1
1 0 0 0 1 1
1 1 1 1 1 1
10 10
1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 1 0 1 0
1 0 0 0 0 0 1 0 1 0
1 0 0 1 0 0 1 0 0 0
1 0 0 0 0 0 1 1 1 1
1 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 0 0 0 1 0 0 0
1 1 1 0 1 0 1 0 1 0
1 1 1 0 0 0 1 0 0 0
案例输出
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0
题目链接:https://nanti.jisuanke.com/t/36117
利用queue队列 模拟bfs 进行解决。
#include<iostream>
#include<queue>
using namespace std;
int cp[501][501];
struct node {
int x;
int y;
};
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int main(){
int time;
queue<node > que;
cin>>time;
while(time--){
int n,m;
que = queue<node >(); //清除队列
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin>>cp[i][j];
if(cp[i][j] > 0 && (i == 1 || i == n || j == 1 || j == m)){ //为了防止如案例一的情况
que.push({i,j});
cp[i][j] = 0;
}
}
}
while(!que.empty()){
int x = que.front().x , y = que.front().y; //取出que中的当前第一个坐标
que.pop(); // 将取出来的坐标出队列
for(int i = 0; i < 4; i++){
int tx = x + dx[i];
int ty = y + dy[i];
if(cp[tx][ty] > 0 && tx >= 1 && tx <= n && ty >= 1 && ty <= m){
que.push({tx,ty});
cp[tx][ty] = 0;
}
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
printf("%d%c", cp[i][j]," \n"[j == m]);
}
}
}
return 0;
}