2020 BIT冬训-图&&DFS&&BFS D - Lake Counting POJ - 2386
Problem Description
在李老板众多的农场中,有这样一片N*M大小的田地,它在下雨后积起了水。
在他的田地中,'W'代表积水,'.'代表土地,一片相互连接的积水叫做“水WA”。(每个格子被认为和相邻的8个格子相连)
现在农场工作人员传回来了田地的航拍图,余队长让你帮他确定有多少个“水WA”。
在他的田地中,'W'代表积水,'.'代表土地,一片相互连接的积水叫做“水WA”。(每个格子被认为和相邻的8个格子相连)
现在农场工作人员传回来了田地的航拍图,余队长让你帮他确定有多少个“水WA”。
Input
* Line 1: N 和 M
* Lines 2..N+1: M个字符一行,每个字符代表余队的农场的土地情况。每个字符中间不包含空格
* Lines 2..N+1: M个字符一行,每个字符代表余队的农场的土地情况。每个字符中间不包含空格
Output
* Line 1: "水WA"的数量
Sample Input
10 12 W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. ..W......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.
Sample Output
3
Hint
样例解释:
左下方,左上方,右边,共三块
左下方,左上方,右边,共三块
访问每一个w并寻找其四周有没有w即可。
用普通的队列写BFS就行。
AC代码如下:
#include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; int n,m,vis[105][105],cnt; char map1[105][105]; int to[8][2]={ 1,0, 0,1, -1,0, 0,-1, //上右下左 1,1, 1,-1, -1,-1, -1,1};//右上,右下,左下,左上 struct node{ int x,y; }; queue<node>q; void bfs(int x,int y){ vis[x][y]=1; int tempx,tempy; node f,temp; f.x=x,f.y=y; q.push(f); while(!q.empty()){ f=q.front(); for(int i=0;i<8;i++){ tempx=f.x+to[i][0],tempy=f.y+to[i][1]; if(tempx<0||tempy<0||tempx==n||tempy==m||map1[tempx][tempy]=='.'||(map1[tempx][tempy]=='W'&&vis[tempx][tempy]==1)) continue; if(map1[tempx][tempy]=='W'){ temp.x=tempx,temp.y=tempy; vis[tempx][tempy]=1; q.push(temp); } } q.pop(); } } int main(){ scanf("%d%d",&n,&m); for(int i=0;i<n;i++) scanf("%s",map1[i]); for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(!vis[i][j]&&map1[i][j]=='W'){ cnt++; bfs(i,j); } printf("%d",cnt); return 0; }

浙公网安备 33010602011771号