Topic links
POJ 2386 Topic
Given a n*m map, ' W ' indicates stagnant water, '. ' Indicates the open space, the water is eight connected, ask how many water blocks. Analysis
The topic is a typical solution to the number of pieces of the basic problem, the idea is to use floodfill (diffuse water filling method), scan a picture, each encounter a ' W ' counter plus one, and deep search or wide search to the adjacent ' W ' fill as '. ' Until there is no water on the chart.
pay attention to the input of the string: either use CIN or use GetChar () to handle the line break. Code
#include <iostream> #include <cstdio> using namespace std;
Char field[1001][1001];
int n,m;
void Dfs_floodfill (int x,int y)//floodfill {field[x][y]= '. ';
for (int dx=-1;dx<=1;dx++) for (int dy=-1;dy<=1;dy++) {int xx=x+dx;
int yy=y+dy; if (xx>=1&&xx<=n&&yy>=1&&yy<=m&&field[xx][yy]== ' W ') DFS_floodfill (
XX,YY);
}} int main () {int i,j,ans;
while (scanf ("%d%d", &n,&m)!=eof) {GetChar ();//Note that there are line breaks before entering the map, it is important.
for (i=1;i<=n;i++) {for (j=1;j<=m;j++) scanf ("%c", &field[i][j]);
GetChar ();
} ans=0;
for (i=1;i<=n;i++) for (j=1;j<=m;j++) if (field[i][j]== ' W ') {
Dfs_floodfill (I,J);
ans++;
} cout<<ans<<endl;
} return 0;
}