题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1241
/* HDU 1241 Oil Deposits --- 入门DFS */ #include <cstdio> int m, n; //n行m列 char mapp[105][105]; /* 将和i,j同处于一个连通块的字符标记出来 */ void dfs(int i, int j){ if (i < 0 || j < 0 || i >= n || j >= m || mapp[i][j] != ‘@‘) return; //此处直接更改为*,省去了一个标记数组,当然也可以用一个标记数组visit记录访问状态 mapp[i][j] = ‘*‘; for (int dr = -1; dr <= 1; dr++) //递归遍历8个方向 for (int dc = -1; dc <= 1; dc++) { if (dr != 0 || dc != 0) dfs(i + dr, j + dc); } } int main() { int cnt; while (scanf("%d%d", &n, &m) && n != 0){ getchar(); for (int i = 0; i < n; ++i) { gets(mapp[i]); } cnt = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (mapp[i][j] == ‘@‘){ ++cnt; dfs(i, j); //调用一次就是一个连通块全部标记成* } } } printf("%d\n", cnt); } return 0; }
时间: 2024-11-03 05:29:23