8个方向求联通块,经典问题。
AC代码
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int maxn = 100 + 5; const int dx[] = {0,0,-1,1,-1,-1,1,1}; const int dy[] = {1,-1,0,0,1,-1,1,-1}; int n, m; char G[maxn][maxn]; int vis[maxn][maxn]; void dfs(int x, int y){ vis[x][y] = 1; for(int i = 0; i < 8; ++i){ int px = x + dx[i], py = y + dy[i]; if(px < 0 || py < 0 || px >= n || py >= m) continue; if(!vis[px][py] && G[px][py] != '*') dfs(px, py); } } int main(){ while(scanf("%d%d", &n, &m) == 2 && n){ memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; ++i) scanf("%s", G[i]); int ans = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j){ if(G[i][j] == '@' && !vis[i][j]){ ++ans; dfs(i, j); } } printf("%d\n", ans); } return 0; }
如有不当之处欢迎指出!