题意是在途中找@块的数量,算上斜方向的。
#include <stdio.h> #include <string.h> #include <stdlib.h> char a[110][110]; int vis[110][110]; int sizev = sizeof(vis); int cou, m, n; int dir[8][2] = {{1, 0}, {1, -1}, {0,1}, {0,-1}, {-1, 0}, {-1,1}, {1, 1}, {-1,-1}}; ///用数组存放上下左右选项 bool check(int x, int y) { if (x >= m || x < 0 || y >= n || y < 0 || vis[x][y]) return false; ///越界与标记过的以后不再走 return true; } void dfs(int x, int y) { int nx, ny; int i; for (i = 0; i < 8; i++) { ///不要用if傻傻地穷举八个方向,代码量太大了 nx = x + dir[i][0]; ny = y + dir[i][1]; if (!check(nx, ny)) continue; vis[nx][ny] = 1; ///标记走过 dfs(nx, ny); ///dfs } } int main() { int i, j; while (~scanf("%d%d", &m, &n) && m) { getchar(); memset(vis, 0, sizev); for (i = 0; i < m; i++) { scanf("%s", a[i]); ///这个数据用scanf("%c",&a[i][j]);有问题 for (j = 0; j < n; j++) { if (a[i][j] == '*') vis[i][j] = 1; } } #if 0 for (i = 0; i < m; i++) { puts(a[i]); } #endif // 1 cou = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (!vis[i][j]) { ///遍历字符数组找到一个没有标记过的点开始DFS vis[i][j] = 1; dfs(i, j); cou++; ///每次搜完一块之后cou+1 } } } printf("%d\n", cou); ///打印出块数 } return 0; }