输入一个m行n列的字符矩阵,统计字符“@”组成多少个八连块。如果两个字符“@”所在的格子相邻(横、竖或者对角线方向),就说它们属于同一个八连块。例如,图中有两个八连块。
思路
dfs求连通块
Code
#include <cstdio>
#include <cstring>
const int maxn = 100;
int m, n, idx[maxn][maxn];//connected component id
char pic[maxn][maxn];void dfs(int r, int c, int id){if(r < 0 || c < 0 || r >= m || c >= n) return;if(pic[r][c] != '@' || idx[r][c] > 0) return;idx[r][c] = id;for(int dx = -1; dx <= 1; dx++)for(int dy = -1; dy <= 1; dy++)if(dx != 0 || dy != 0) dfs(r+dx, c+dy, id);
}
int main(){ while(scanf("%d%d", &m, &n) == 2 && m && n){for(int i = 0; i < m; i++) scanf("%s", pic[i]);memset(idx, 0, sizeof(idx));int cnt = 0;for(int i = 0; i < m; i++)for(int j = 0; j < n; j++)if(idx[i][j] == 0 && pic[i][j] == '@') dfs(i, j, ++cnt);//连通分量数量++ printf("%d\n", cnt);}return 0;
}