经典的dfs搜索入门题,程序简洁漂亮
#include<iostream>
using namespace std;
int N, M;
char field[105][105];
void dfs(int i, int j) {
field[i][j] = '.';
//八领域都有水
for(int l=-1;l<=1;l++)
for(int v = -1; v <= 1; v++){
if ((i+l<N)&&(i + l >= 0)&&(j + v >= 0)&&(j + v<M)){
if ((field[i + l][j + v] == 'W'))
dfs(i + l, j + v);
}
}
}
int main() {
cin >> N >> M;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
cin >> field[i][j];
int res = 0;
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
if (field[i][j] == 'W') {
dfs(i, j);
res++;
}
cout << res << endl;
//system("pause");
}