Lake Counting——DFS
首次写文章,请多多指教(菜鸟一枚,仅供参考,算法题)
Description
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.(这句话我想了好久,我觉得应该是以一个点为中心,然后找这个中心的四周有没有water ,如果有按照这个water 继续查找。就是一个小正方形中心有一个点,四周的点数就是8,也就是8联通。当一个点四周没有water 时就是一个pond。)
Given a diagram of Farmer John’s field, determine how many ponds he has.
题目大意:有一个m*n的矩阵,矩阵里面的元素是’W’和’.’。如果’W’四周没有’W’全都是’.'那么就是一个池塘啦。所以只需要遍历数组内的元素,就可以查到有几个池塘了。
Input
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.
Output
Line 1: The number of ponds in Farmer John’s field.
Sample Input
Sample Output
3
例子中的池塘就是这三个啦。
然后就是我的代码输入啦
#include <iostream>
#include <cstring>
using namespace std;
char s[105][105];
int m,n,idx[105][105];
void dfs(int r,int l,int id){
if(r<0||r>=m||l<0||l>=n)//判断是否越界
return;
else if(idx[r][l]>0||s[r][l]!='W')//判断是否访问过||以及是否为水坑
return;
else{
idx[r][l]=id;
for(int dr=-1;dr<=1;dr++){//8联通中存在水坑
for(int dl=-1;dl<=1;dl++){
if(dr!=0||dl!=0){
dfs(r+dr,l+dl,id);//联通中某个方位存在水坑,进入dfs函数中
}
}
}
}
}
int main()
{
int cot=0;
cin>>m>>n;
/*将输入的图形储存至数组中*/
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>s[i][j];
}
}
//判断输出图像是否正常
/*for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cout<<s[i][j];
}
cout<<endl;
}*/
memset(idx,0,sizeof(idx));//将idx位置后面sizeof(idx)用0代替
//计算庄园之中有多少个池塘,每次遍历都会增加池塘的个数
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(idx[i][j]==0&&s[i][j]=='W')
dfs(i,j,++cot);
}
}
cout<<cot;
return 0;
}