Source: http://poj.org/problem? Id = 2386
Lake counting
Time limit:1000 ms |
|
Memory limit:65536 K |
Total submissions:20124 |
|
Accepted:10139 |
Description Due to recent rains, water has pooled in varous 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 wowould like to figure out How sort 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 distriof Farmer John's field, determine how he 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 12W........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 Usaco 2004 November |
Question: Question !!! Two mistakes in one sentence:, how many waters are there in a 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. At first, we understood that two "W" would be considered as one piece of water-and there was another direction. We only considered the four directions of the upper, lower, and lower directions, leading to a long Wa ..
Problem: DFS (it does not feel like a standard DFS and does not need to be traced back )....
AC code:
#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;}