Starting from any W, the adjacent part is replaced. After one DFS operation, all the WS connected to the initial W will be replaced with '.', so until w no longer exists in the figure, the total number of DFS operations is the answer. Eight statuses are transferred in eight directions. Each grid is called once as a DFS parameter, so the complexity is O (8 × n × m) = O (n × m ).
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;char map[110][110];int dis[8][2]={{0,1},{1,0},{-1,0},{0,-1},{1,1},{-1,-1},{-1,1},{1,-1}};int n,m;void dfs(int x,int y){ map[x][y]='.'; for(int i=0;i<8;i++) { int xx=x+dis[i][0]; int yy=y+dis[i][1]; if(xx<0||xx>=n||yy<0||yy>=m) continue; if(map[xx][yy]=='W') { dfs(xx,yy); } } return;}int main(){ //freopen("d:\\test.txt","r",stdin); while(cin>>n>>m) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>map[i][j]; } } int ans=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(map[i][j]=='.') continue; dfs(i,j); ans++; } } cout<<ans<<endl; } return 0;}
Poj2386 Lake counting (DFS)