AcWing 1113. 红与黑(bfs)
原题链接
简单
作者:
qiao
,
2022-01-23 16:36:38
,
所有人可见
,
阅读 21
C++ 代码
#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 25;
char g[N][N];
int n, m;
int cnt;
int dir[4][2] = { 1,0,-1,0,0,-1,0,1 };
int vis[N][N];
bool check(int x, int y)
{
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == '.')return true;
else return false;
}
void bfs(PII s)
{
queue<PII> q;
q.push(s); cnt = 1;
while (q.size())
{
auto t = q.front(); q.pop();
for (int i = 0; i < 4; i++)
{
int xx = t.x + dir[i][0];
int yy = t.y + dir[i][1];
if (!vis[xx][yy]&&check(xx,yy))
{
cnt++;
vis[xx][yy] = 1;
q.push({ xx,yy });
}
}
}
}
int main()
{
PII s;
while (true)
{
cin >> m >> n; if (m == 0 && n == 0)return 0;
for (int i = 0; i < n; i++)
{
scanf("%s", g[i]);
for (int j = 0; j < m; j++)if (g[i][j] == '@')s = { i,j };
}
memset(vis, 0, sizeof(vis));
bfs(s);
cout << cnt << endl;
}
}