题目描述:原题链接
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.
Given a diagram of Farmer John’s field, determine how many ponds he has.
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
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
题目大意:给你一副图,其中’W’代表池塘,’.'代表土地,问现在这幅图中有多少个池塘,如果一个池塘的八个方向上如果有池塘,则只算一个,类似于连通块。
解法一:BFS
思路:
因为N,M都很小,所以可以利用队列,枚举每一个点作为起点进行标准的BFS过程。
#include <iostream>
#include <queue>
using namespace std;
char map[110][110];
int dir[8][2]={ {0,1},{0,-1},{-1,0},{1,0},{-1,-1},{-1,1},{1,-1},{1,1} };
struct node{
int x,y;
};
queue<node>q;
node now,next;
void BFS(int i,int j)
{
while(!q.empty())
{
now=q.front();
q.pop();
for(int k=0;k<8;k++)
{
next.x=now.x+dir[k][0];
next.y=now.y+dir[k][1];
if(map[next.x][next.y]=='W')
{
q.push(next);
map[next.x][next.y]='*';
}
}
}
}
int main()
{
int N,M,len=0;
while(cin>>N>>M)
{
for(int i=1;i<=N;i++)
for(int j=1;j<=M;j++)
cin>>map[i][j];
for(int i=1;i<=N;i++)
{
for(int j=1;j<=M;j++)
{
if(map[i][j]=='W')
{
len++;
now.x=i;
now.y=j;
q.push(now);
map[now.x][now.y]='*';
BFS(i,j);
}
}
}
cout<<len<<endl;
}
return 0;
}
解法二:DFS
思路:
将BFS中的队列改成栈即可。
#include <iostream>
#include <stack>
using namespace std;
char map[110][110];
int dir[8][2]={ {0,1},{0,-1},{-1,0},{1,0},{-1,-1},{-1,1},{1,-1},{1,1} };
struct node{
int x,y;
};
stack<node>q;
node now,next;
void DFS(int i,int j)
{
while(!q.empty())
{
now=q.top();
q.pop();
for(int k=0;k<8;k++)
{
next.x=now.x+dir[k][0];
next.y=now.y+dir[k][1];
if(map[next.x][next.y]=='W')
{
q.push(next);
map[next.x][next.y]='*';
}
}
}
}
int main()
{
int n,m,len=0;
while(cin>>n>>m)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>map[i][j];
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(map[i][j]=='W')
{
len++;
now.x=i;
now.y=j;
q.push(now);
map[now.x][now.y]='*';
DFS(i,j);
}
}
}
cout<<len<<endl;
}
return 0;
}