题目
1388:Lake Counting
查看提交统计提问
总时间限制: 1000ms 内存限制: 65536kB
描述
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (‘.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John’s field, determine how many ponds he has.
输入
-
Line 1: Two space-separated integers: N and M
-
Lines 2…N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
输出 -
Line 1: The number of ponds in Farmer John’s field.
样例输入
10 12
W…WW.
.WWW…WWW
…WW…WW.
…WW.
…W…
…W…W…
.W.W…WW.
W.W.W…W.
.W.W…W.
…W…W.
样例输出
3
翻译
题目
由于due最近的降雨,农民约翰的田地field里的各个various 地方都积水pooled 了,
用N x M(1<=N<=100;1<=M<=100)正方形squares的矩形rectangle 表示represented 。
每个正方形包含水(“W”)或旱地(“.”)。
农夫约翰想弄清楚figure 他的田里形成了多少池塘ponds 。池塘是一组相连connected 的正方形,其中有水,
其中一个正方形被认为considered 与它的所有八个邻居相邻adjacent 。
给出农夫约翰田地的示意图diagram ,确定determine 他有多少池塘。
输入
*第1行:两个空格分隔的整数:N和M
*第2…N+1:M个字符每行代表representing 农民约翰的田地的一行。每个字符都是“W”或“.”。
字符之间没有空格。
输出
*第1行:农夫约翰田地里的池塘数量。
理解
精力都花在翻译上,没啥就是宽搜。
'W’就算作一个池塘,而且周围8个点中的’W’都算入该池塘。
看下整个field有几个ponds。
代码
#include <bits/stdc++.h>
using namespace std;
struct squares{
int x,y;
};
int n,//行
m,//列
ans,
d[8][2]={{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1}};
char field[110][110];
bool k[110][110];
void view(){
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)cout<<field[i][j]<<" ";
cout<<endl;
}
}
bool ok(int x,int y){
return x>=1&&x<=n&&y>=1&&y<=m&&!k[x][y]&&field[x][y]= =‘W’;
}
int main(){
//freopen(“data.cpp”,“r”,stdin);
cin>>n>>m;
cin.get();//撇清换行符号
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
field[i][j]=cin.get();
}
cin.get();
}
//view();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)//遍历每块土地
if(field[i][j]==‘W’&&!k[i][j]){//如果是水,而且还没算成哪块水塘
k[i][j]=1;ans++;//以该块土地为一个池塘,
queue q;q.push(squares{i,j});//队列
while(!q.empty()){//队列非空就宽搜
squares s=q.front();q.pop();//取得对首元素
for(int o=0;o<8;o++){//遍历8个方向
int x=s.x+d[o][0],y=s.y+d[o][1];
if(ok(x,y)){//如果是水,并且没算过,都算入该池塘
k[x][y]=1;q.push(squares{x,y});
}
}
}
}
cout<<ans;
return 0;
}
小结
提高阅读理解能力