洛谷P1162 填涂颜色
蒟蒻第一次写bfs
别问我为啥第一次写
(以前发现dfs貌似是万能的
一道签到题
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<string> #include<ctime> #include<queue> #include<set> #include<stack> #include<map> #include<algorithm> #define maxn 100001 #define INF 0x3f3f3f3f #define inf 0x3f #define maxm 1001 using namespace std; int n,dx[]={-1,1,0,0},bx,by,dy[]={0,0,-1,1},vis[31][31],a[31][31]; queue<int> q; void bfs(int x,int y){ vis[x][y]=1; q.push(x); q.push(y); while(!q.empty()){ int u=q.front(); q.pop(); int v=q.front(); q.pop(); for(int i=0;i<4;i++){ int xx=u+dx[i]; int yy=v+dy[i]; if(a[xx][yy]==0&&xx>0&&yy>0&&xx<=n&&yy<=n&&vis[xx] [yy]==0){ vis[xx][yy]=1; q.push(xx); // q.pop(); q.push(yy); // q.pop(); } } } } 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) vis[i][j]=1; } } for(int i=1;i<=n;i=i+n-1){ for(int j=1;j<=n;j++){ if(vis[i][j]) continue; bfs(i,j); } } for(int i=1;i<=n;i=i+n-1){ for(int j=1;j<=n;j++){ if(vis[j][i]) continue; bfs(j,i); } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(vis[i][j]==0) cout<<"2"<<" "; else cout<<a[i][j]<<" "; } cout<<endl; } return 0; }