做为一个(大佬) 新手 广搜怎么能不会呢? #include <bits/stdc++.h>//万能头 using namespace std; int n,m,ans; char a[105][105]; bool vis[105][105]; struct Pos { int x, y; Pos(int ax=0,int ay=0) { x=ax; y=ay; } }; void bfs(int x,int y) { queue<Pos> q; q.push(Pos(x,y)); while(!q.empty()) { Pos now = q.front(); q.pop(); int x=now.x,y=now.y; if(x<1 || x>n) continue; if(y<1 || y>m) continue; if(a[x][y]=='.') continue;//遇墙跳过 if(vis[x][y]) continue; vis[x][y]=1; q.push(Pos(x,y-1));//加入八方的洼地 q.push(Pos(x,y+1)); q.push(Pos(x-1,y)); q.push(Pos(x+1,y)); q.push(Pos(x-1,y-1)); q.push(Pos(x+1,y+1)); q.push(Pos(x-1,y+1)); q.push(Pos(x+1,y-1)); } } int main() { cin>>n>>m; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>a[i][j]; } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(a[i][j]!='.' && vis[i][j]!=1){ ans++; bfs(i,j); } } } cout<<ans; return 0; }