BFS:输入的时候标记一下出发点,从这个点开始bfs,把这个点能延申的所有黑砖标记 记录在vis数组,标记完成后,两个for循环遍历vis数组,ans++
#include<iostream>
#include <queue>
using namespace std;
int w, h, stx, sty;
const int N = 1000;
int map[N][N];
int vis[N][N];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,-1,0,1 };
struct Node
{
int x; int y;
};
queue<Node>q;
void bfs(int x, int y)
{
q.push({ x,y }); vis[x][y] = 1;
while (!q.empty())
{
Node p = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if (nx < 0 || ny < 0 || nx >= h || ny >= w || vis[nx][ny] == 1 || map[nx][ny] == 1)continue;
else
{
q.push({ nx,ny });
vis[nx][ny] = 1;
}
}
}
}
int main()
{
cin >> w >> h;
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
char s; cin >> s;
if (s == '.')map[i][j] = 0;
else if (s == '#')map[i][j] = 1;
else if (s == '@') {
map[i][j] = 0;
stx = i, sty = j;
}
}
}
bfs(stx, sty);
int ans = 0;
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
if (vis[i][j])
{
ans++;
}
}
}
cout << ans << endl;
return 0;
}