一道裸的 \(bfs\) ,然而还是折腾到我了。
/**
* hdu1312 Red and Black
* bfs
*/
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
#define pii pair<int,int>
#define x first
#define y second
const int N = 22;
char mp[N][N];
int dir[][2] = {
-1, 0,
0, 1,
1, 0,
0, -1
};
int bfs(int sx, int sy)
{
int ans = 0;
queue<pii> Q;
Q.push(pii{sx, sy});
while (!Q.empty()) {
pii q = Q.front(); Q.pop();
++ans;
for (int i = 0; i < 4; ++i) {
int tx = q.x+dir[i][0];
int ty = q.y+dir[i][1];
if (mp[tx][ty] != ‘.‘) continue;
Q.push(pii{tx, ty});
mp[tx][ty] = ‘#‘;
}
}
return ans;
}
int main()
{
int n, m; // n行m列
int sx, sy; // ‘@’所在位置
while (~scanf("%d%d", &m, &n) && (n|m)) {
for (int j = 1; j <= m; ++j) mp[0][j] = mp[n+1][j] = ‘#‘;
for (int i = 1; i <= n; ++i) {
getchar();
mp[i][0] = mp[i][m+1] = ‘#‘;
for (int j = 1; j <= m; ++j) {
mp[i][j] = getchar();
if (mp[i][j] == ‘@‘) sx = i, sy = j;
}
}
/*
cout << endl;
for (int i = 0; i <= n+1; ++i) {
for (int j = 0; j <= m+1; ++j)
cout << mp[i][j];
cout << endl;
}
cout << endl;
*/
cout << bfs(sx, sy) << endl;
}
// cout << n << ‘ ‘ << m;
return 0;
}
原文:https://www.cnblogs.com/zbhfz/p/14312229.html