“秒懂”
2024-12-16 21:03:14
发布于:广东
27阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
const int max_n = 40;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int n;
int mp[max_n][max_n];
int vis[max_n][max_n];
struct Node{
int x, y;
};
void bfs() {
queue<Node> q;
for(int i=0;i<n;i++){
if(mp[0][i]==0){
q.push({0,i});
vis[0][i]=1;
}
if(mp[n-1][i]==0){
q.push({n-1,i});
vis[n-1][i]=1;
}
if(mp[i][0]==0){
q.push({i,0});
vis[i][0]=1;
}
if(mp[i][n-1]==0){
q.push({i,n-1});
vis[i][n-1]=1;
}
}
while(!q.empty()){
Node w=q.front();
q.pop();
for(int k=0;k<4;k++){
int tx=w.x+dx[k];
int ty=w.y+dy[k];
if (tx>=0&&tx<n&&ty>=0&&ty<n&&!vis[tx][ty]&&mp[tx][ty]==0){
vis[tx][ty] = 1;
q.push({tx, ty});
}
}
}
}
int main(){
cin >> n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
cin >> mp[i][j];
}
}
bfs();
for (int i=0;i<n;i++){
for (int j=0;j<n; j++){
if (mp[i][j]==0&&!vis[i][j]){
cout <<2<<" ";
}else{
cout <<mp[i][j]<< " ";
}
}
cout << endl;
}
return 0;
}
这里空空如也
有帮助,赞一个