题意:求连通块个数。
分析:dfs。
#include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const double pi = acos(-1.0); const double eps = 1e-8; const int MAXN = 100 + 10; const int MAXT = 40 + 10; using namespace std; int cnt; int m, n; int vis[MAXN][MAXN]; char a[MAXN][MAXN]; int judge(int i, int j){ return i >= 0 && i < m && j >= 0 && j < n; } void dfs(int x, int y){ vis[x][y] = 1; for(int i = 0; i < 8; ++i){ int tmpx = x + dr[i]; int tmpy = y + dc[i]; if(judge(tmpx, tmpy) && !vis[tmpx][tmpy] && a[tmpx][tmpy] == '@'){ dfs(tmpx, tmpy); } } } int main(){ while(scanf("%d%d", &m, &n) == 2){ if(!m && !n) return 0; memset(vis, 0, sizeof vis); cnt = 0; for(int i = 0; i < m; ++i) scanf("%s", a[i]); for(int i = 0; i < m; ++i){ for(int j = 0; j < n; ++j){ if(a[i][j] == '@' && !vis[i][j]){ ++cnt; dfs(i, j); } } } printf("%d\n", cnt); } }