八连块dfs

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int MAX = 100;
 5 char arr[MAX][MAX];
 6 int n,m;
 7 
 8 void init();
 9 void solve();
10 void dfs(int x,int y);
11 
12 void init(){
13     cin>>n>>m;//输入行数列数 
14     for(int i=0;i<n;i++){
15         for(int j=0;j<m;j++){
16             cin>>arr[i][j];//输入“w 和 . ” 
17         }
18     }    
19     solve();
20 } 
21 
22 void solve(){
23     int result = 0;
24     for(int i=0;i<n;i++){
25         for(int j=0;j<m;j++){
26             if(arr[i][j] == 'w'||arr[i][j] == 'W'){
27                 dfs(i,j);//搜索(i,j)周围的 w 
28                 result++;
29             }
30         }
31     }
32     cout<<"八连块的数量为"<<result<<endl; 
33 }
34 
35 void dfs(int x,int y){
36     arr[x][y] = '.';
37     //遍历(x,y)周围的八个位置,搜索 w 
38     for(int dx=-1;dx<=1;dx++){
39         for(int dy=-1;dy<=1;dy++){
40             int nx=x+dx;
41             int ny=y+dy;
42             if(nx>=0&&nx<=n&&ny>=0&&ny<=m&&(arr[nx][ny]=='w'||arr[nx][ny] == 'W')){
43                 dfs(nx,ny);
44             }
45         }
46     }
47     
48 }
49 
50 int main(){
51     init();
52     return 0;
53 }
原文地址:https://www.cnblogs.com/xuecl/p/12362675.html