第一部分:题目
题目链接:http://poj.org/problem?id=2386
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.
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.
* 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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
第二部分:思路
深度优先搜索,讲白点就是每种可能都扫一遍。这题的意思就是找出n*m区域中有多少水洼:就是相连的:上下左右还有对角。那么就可以从左上角开始,遇到W就把它置为'.',然后看它的8个”邻居“是否是W,是的话把它置为‘.’,并且以它为中点再看它的8个邻居。这样整个过程结束就相当于把一个水洼填满了'.'。所以做了多少次就相当于有多少处水洼。
第三部分 :代码
#include<iostream> using namespace std; char field[100][100]; int count=0; int n,m; void dfs(int i,int j) { field[i][j]='.'; int dx,dy; //用循环做8个方向的处理 for(dx=-1;dx<=1;dx++) { for(dy=-1;dy<=1;dy++) { int x,y; x=i+dx; y=j+dy; if(x>=0&&y>=0&&field[x][y]=='W') { dfs(x,y); } } } } int main() { int j,i; cin>>n>>m; for(i=0;i<n;i++) { for(j=0;j<m;j++) { cin>>field[i][j]; } } for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(field[i][j]=='W') { dfs(i,j); count++; } } } cout<<count<<endl; return 0; }