描述
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
解题思路:
从图中找一个w开始深搜,找其邻接的八个节点中是否存在w点,若存在w点,再进行DFS深搜,直到图中没有w点为止,记录一下重新开始了几遍深搜,就得到水塘的个数。水塘(w连成一片)。
Code:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int N,M,sum=0;
vector<vector<char>>G;
void DFS(int r,int c){//行 列
G[r][c]='.';
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++)//八个方向移动 查找是否存在W点
if((r+i>=0&&r+i<N)&&(c+j>=0&&c+j<M))//判断是否为水坑 还要保证不越界
if(G[r+i][c+j]=='W')//找到W由这个点进行深搜
DFS(r+i,c+j);
}
}
int main(){
cin>>N>>M;
G.resize(N);
for(int i=0;i<N;i++)
G[i].resize(M);
char ch;
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
cin>>G[i][j];//存图
for(int i=0;i<N;i++)
for(int j=0;j<M;j++){
if(G[i][j]=='W'){//查找图中是否还存在W点----是否还存在水塘
sum++;//若存在水塘数加1
DFS(i,j);//从这个W点开始深搜
}
}
cout<<sum;
return 0;
}