3 solutions
-
1
经典的flood fill 问题 bfs
#include<iostream> #include<queue> using namespace std; typedef pair<int,int> PAII; const int N=1010; char ch[N][N]; bool st[N][N]; int dx[4]={0,0,1,-1}; int dy[4]={1,-1,0,0}; int n,m; void bfs(int x,int y) { queue<PAII> q; q.push({x,y}); st[x][y]=true; while(q.size()) { auto t=q.front(); q.pop(); int a=t.first,b=t.second; for(int i=0;i<4;i++) { int xx=a+dx[i],yy=b+dy[i]; if(xx<0||yy<0||xx>=n||yy>=m) continue; if(ch[xx][yy]=='#'&&!st[xx][yy]) { q.push({xx,yy}); st[xx][yy]=true; } } } } int main(){ cin>>n>>m; for(int i=0;i<n;i++) for(int j=0;j<m;j++) cin>>ch[i][j]; int sum=0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { if(!st[i][j]&&ch[i][j]=='#') { bfs(i,j); sum++; } } cout<<sum; return 0; }
Information
- ID
- 720
- Time
- 1000ms
- Memory
- 64MiB
- Difficulty
- 1
- Tags
- # Submissions
- 62
- Accepted
- 41
- Uploaded By