来源:http://poj.org/problem?id=2386
Lake Counting
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 Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side. Source |
题意:题意题意!!! 一句话两处理解错误,,,,, 求一块田野里有多少块水域~~ 里面最关键的一句:A pond is a connected set of squares with water in them, where a square
is considered adjacent to all eight of its neighbors.
开始理解成至少要两个"W"才算一块水域---还有方向,只考虑上下左右四个方向,导致一直WA..
题解: DFS(感觉又不是标准的DFS,不需要回溯)....
AC代码:
#include<iostream> #include<string> using namespace std; int dir[8][2]={ {0,1},{0,-1}, {1,0},{-1,0}, {1,1},{1,-1}, {-1,-1},{-1,1} }; string map[105]; int dx,dy,count=0; bool flag; void dfs(int x,int y){ for(int i=0;i<8;i++){ int tempx=x+dir[i][0],tempy=y+dir[i][1]; if(tempx>=0&&tempx<dx&&tempy>=0&&tempy<dy&&map[tempx][tempy]=='W'){ map[tempx][tempy]='.'; dfs(tempx,tempy); } } } int main() { cin>>dx>>dy; for(int i=0;i<dx;i++) cin>>map[i]; for(int i=0;i<dx;i++) for(int j=0;j<dy;j++){ if(map[i][j]=='W'){ count++; map[i][j]='.'; dfs(i,j); } } cout<<count<<endl; return 0; }
POJ 2386 Lake Counting,布布扣,bubuko.com
原文地址:http://blog.csdn.net/mummyding/article/details/38419997