C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
DFS
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 25;
int n, m;
char g[N][N];
bool st[N][N];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; // 偏移量
int dfs(int x, int y) {
int cnt = 1;
st[x][y] = true;
for (int i = 0; i < 4; i ++) { // 枚举上下左右四个方向
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m) continue; // 越界
if (g[a][b] != '.') continue; // 不是黑色
if (st[a][b]) continue; // 已经被搜过
cnt += dfs(a, b);
}
return cnt;
}
int main() {
while (cin >> m >> n, n || m) {
for (int i = 0; i < n; i ++) cin >> g[i];
int x, y;
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
if (g[i][j] == '@')
x = i, y = j;
memset(st, 0, sizeof st);
cout << dfs(x, y) << endl;
}
return 0;
}