原题网址
本题是我第一个用bfs的题目,bfs是队里的shawnzhou大佬教我的,在这里先感谢他一下啦 这个题的思路也是他提供的,还是需要一定的练习才行鸭!!
对于本题来说的话,先将外面的0涂成2 然后遍历图,将0和2涂反色就可以了 注意bfs的使用哦~
代码实现:
#include<bits/stdc++.h>
using namespace std;
int a[100][100];
bool vis[100][100];
int n;
struct node {
int x;
int y;
};
int dx[]={0,1,-1,0};
int dy[]={1,0,1,-1};
bool check(int x,int y) {
if(x>=0&&x<=n+1&&y>=0&&y<=n+1)
return true;
return false;
}
void bfs(int x,int y) {
queue<node>q;
node s;
s.x=x;
s.y=y;
q.push(s);
a[s.x][s.y]=2;
vis[s.x][s.y]=true;
while(!q.empty()) {
node u=q.front();
q.pop();
for(int i=0;i<4;i++) {
node w;
w.x=u.x+dx[i];
w.y=u.y+dy[i];
if(check(w.x,w.y)) {
if((!vis[w.x][w.y])&&a[w.x][w.y]==0) {
vis[w.x][w.y]=true;
a[w.x][w.y]=2;
q.push(w);
}
}
}
}
}
int main() {
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>a[i][j];
bfs(0,0);
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
if(a[i][j]==0)
cout<<2<<" ";
if(a[i][j]==1)
cout<<1<<" ";
if(a[i][j]==2)
cout<<0<<" ";
}
cout<<endl;
}
}
队列还真是基础呢