题目链接如下:
Online Judge
这道题我一开始用连通集来做的,搜了些测试样例都能过,但不知道为什么就是WA。后来写了个DFS。本来想把连通集的写法改好了再一并记录下来的,但花了好几个钟头怎么都调不过,很无奈。
DFS的代码如下:
#include <cstdio>
// #define debugint m, n, cnt;
char matrix[100][100];
int dx[] = {-1, 0, 1, 1, 1, 0, -1, -1};
int dy[] = {1, 1, 1, 0, -1, -1, -1, 0};void dfs(int u, int v){for (int i = 0; i < 8; ++i){if (u + dx[i] >= 0 && u + dx[i] < m && v + dy[i] >= 0 && v + dy[i] < n && matrix[u + dx[i]][v + dy[i]] == '@'){matrix[u + dx[i]][v + dy[i]] = ' ';dfs(u + dx[i], v + dy[i]);}}
}int main(){#ifdef debugfreopen("0.txt", "r", stdin);freopen("2.txt", "w", stdout);#endifwhile (scanf("%d %d\n", &m, &n) == 2 && m){cnt = 0;for (int i = 0; i < m; ++i){scanf("%s", matrix[i]);}for (int i = 0; i < m; ++i){for (int j = 0; j < n; ++j){if (matrix[i][j] == '@'){++cnt;matrix[i][j] = ' ';dfs(i, j);}}}printf("%d\n", cnt);}#ifdef debugfclose(stdin);fclose(stdout);#endifreturn 0;
}