Flood Fill-dfs

Farmer John has a rectangular land N * MN * M's.
Recently, due to rainfall, part of the land covered by water.
Now with a character matrix to express his land.
Within each cell, if it contains rainwater, with the "W" indicates, if excluding rain, use. "" FIG.
Now, John wanted to know his piece of land in the formation of a number of ponds.
Each cell is connected to the water can be seen as a collection pond.
Each cell considered thereon, is connected to the lower, left, right, upper left, upper right, lower left, lower right eight neighboring cells.
Please output the total number of pieces pond, that "W" block connected to the matrix how many pieces there are.
Input format
The first line contains two integers NN and MM.
Next NN lines, each line containing MM characters, characters "W" or ".", To indicate the status of the water rectangle of land, with no spaces between characters.
Output format
output an integer representing the number of ponds.
Data range
1≤N, M≤10001≤N, M≤1000
input sample:
10 12 is
. W is ... WW of
.WWW the WWW ...
. ... WW of WW of ...
. ... WW of
... W is ...
... ... W is W is ...
.WW ... WW of.
W ... the WWW.
.WW ... W.
... W ... W.

Sample output:
3

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=1010,M=N*N;
#define x first
#define y second 
typedef pair<int,int> PII;
int n,m;
char g[N][N];
PII q[M];
bool st[N][N];
void bfs(int sx,int sy){
 int hh=0,tt=0;
 q[0]={sx,sy};
 st[sx][sy]=true;
 while(hh<=tt){
  PII t=q[hh++];
  for(int i=t.x-1;i<=t.x+1;i++)
    for(int j=t.y-1;j<=t.y+1;j++){
     if(i==t.x && j==t.y)   continue;
     if(i<0 || i>=n || j<0 || j>=m)   continue;
     if(g[i][j]=='.' || st[i][j])   continue;
     q[++tt]={i,j};
     st[i][j]=true;
    }
 }
}
int main(){
 scanf("%d%d",&n,&m);
 for(int i=0;i<n;i++)   scanf("%s",g[i]);
 int cnt=0;
 for(int i=0;i<n;i++)
    for(int j=0;j<m;j++)
       if(g[i][j]=='W'&& !st[i][j]){
        bfs(i,j);
        cnt++;
    }
 printf("%d\n",cnt);
 return  0;
}
发布了37 篇原创文章 · 获赞 28 · 访问量 3821

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/104409493