chenhanze @ 2024-08-05 11:14:37
#include<bits/stdc++.h>
using namespace std;
queue <int> l,r;
int dx[4]= {1,0,-1,0};
int dy[4]= {0,1,0,-1};
int n,m;
int a[303][303];
int gh[303][303];
int bfs(int b,int c) {
gh[b][c]=1;
l.push(b);
r.push(c);
while(!l.empty()&&!r.empty()) {
int xx=l.front();
int yy=r.front();
if(!l.empty()){
l.pop();r.pop();}
for(int i=0; i<=3; i++) {
int x=xx+dx[i];
int y=yy+dy[i];
if(!gh[x][y]&&x>0&&x<=n&&y>0&&y<=n) {
gh[x][y]=1;
l.push(x);
r.push(y);
}
}
}
}
int main() {
cin>>n;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++) {
cin>>a[i][j];
if(a[i][j]==1)
gh[i][j]=1;
}
for(int i=1; i<=n; i++) {
if(a[i][1]==0) bfs(i,1);
if(a[n][i]==0) bfs(n,i);
if(a[1][i]==0) bfs(1,i);
if(a[i][n]==0) bfs(i,n);
}
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
if(gh[i][j]!=1&&a[i][j]!=1) {
a[i][j]=2;
}
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
谢谢!
by wuzhitong @ 2024-08-05 11:21:10
by 朱梓煊ZZX @ 2024-08-05 11:21:34
@chenhanze 数组越界
if(!gh[x][y]&&x>0&&x<=n&&y>0&&y<=n) {
先判断x,y是否越界再判gh[][]应该就可以了
by chenhanze @ 2024-08-05 11:22:29
@朱梓煊ZZX 谢谢
by 朱梓煊ZZX @ 2024-08-05 11:23:36
@chenhanze 等等,好像还RE
by chenhanze @ 2024-08-05 11:25:18
@朱梓煊ZZX 确实是
by chenhanze @ 2024-08-05 11:29:14
@朱梓煊ZZX 已经AC了
by zhouyuyan__mutao @ 2024-08-14 16:29:14
@chenhanze 你可以把数组开大一点
by apsp1 @ 2024-08-17 19:33:13
@chenhanze 最后怎么解决的一样的问题求
by chenhanze @ 2024-08-19 08:25:49
@apsp1 把int bfs 改成 void bfs