题目链接
思路
dfs,注意行列!
时间复杂度
$$ 每组O(NM) $$
代码
#include <cstdio>
using namespace std;
const int MAXN = 25;
char s[MAXN][MAXN];
int n, m;
int ans;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
bool check(int x, int y) {
if (1 <= x && x <= n && 1 <= y && y <= m && s[x][y] == '.') {
return true;
} else {
return false;
}
}
void dfs(int x, int y) {
s[x][y] = '#';
ans++;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (check(xx, yy)) {
dfs(xx, yy);
}
}
}
int main() {
while (scanf("%d%d", &m, &n), n + m){
for (int i = 1; i <= n; i++) {
scanf("%s", s[i] + 1);// no &
}
ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i][j] == '@') {
dfs(i, j);
}
}
}
printf("%d\n", ans);
}
return 0;
}