题干 c++代码 #include <iostream> #include <algorithm> using namespace std; #define Max_M 100 #define Max_N 100 char a[Max_M][Max_N],M,N; void dfs(int x,int y) {//先把w替换成.//然后遍历8个方向a[x][y] = '.';for(int dx = -1;dx <= 1;dx++){for(int dy = -1;dy <= 1;dy++){int nx = x + dx;int ny = y + dy;if(nx > 0&&nx < M&&ny > 0&&ny < N&&a[nx][ny] == 'W')dfs(nx,ny);}} } int main() {int i,j,ans = 0;//读入该图cin >> M >> N;for(i = 0;i < M;i++)for(j = 0;j < N;j++)cin >> a[i][j];for(i = 0;i < M;i++){for(j = 0;j < N;j++){if(a[i][j] == 'W'){dfs(i,j);ans++;}}}cout << ans << endl;return 0; }