DFS解法
#include <bits/stdc++.h>
using namespace std;
char maze[25][25];
bool vis[25][25];
const int dir[][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int n, m, res;
void init() {
memset(vis, 0, sizeof vis);
res = 0;
}
void dfs(int x, int y) {
if(x <= 0 || x > n || y <= 0 || y > m || vis[x][y] || maze[x][y] == '#') return;
vis[x][y] = true;
res++;
for(int i = 0; i < 4; i++)
dfs(x + dir[i][0], y + dir[i][1]);
}
int main()
{
while(cin >> m >> n, m) {
init();
for(int i = 1; i <= n; i++) scanf("%s", maze[i] + 1);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(maze[i][j] == '@') dfs(i, j);
cout << res << endl;
}
return 0;
}
BFS解法
#include <bits/stdc++.h>
using namespace std;
char maze[25][25];
bool vis[25][25];
const int dir[][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int n, m, res;
void init() {
memset(vis, 0, sizeof vis);
res = 0;
}
void bfs(int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
vis[x][y] = true;
while(q.size()) {
auto now = q.front(); q.pop();
res++;
for(int i = 0; i < 4; i++) {
int dx = now.first + dir[i][0];
int dy = now.second + dir[i][1];
if(dx <= 0 || dx > n || dy <= 0 || dy > m || vis[dx][dy] || maze[dx][dy] == '#') continue;
vis[dx][dy] = true;
q.push({dx, dy});
}
}
}
int main()
{
while(cin >> m >> n, m) {
init();
for(int i = 1; i <= n; i++) scanf("%s", maze[i] + 1);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
if(maze[i][j] == '@') bfs(i, j);
cout << res << endl;
}
return 0;
}