程序如下:
#include <iostream>
#include <queue>
#define SIZE 2001
using namespace std;
struct node
{
int x, y;
};
char a[SIZE][SIZE];
bool v[SIZE][SIZE];
int res;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
node _next;
queue<node> q;
int _up(int x, int y) // 上
{
if (a[x][y] == '#') // 是障碍则停止
{
return 0;
}
if (a[x][y] == 'G') // 炸到僵尸
{
return 1 + _up(x - 1, y);
}
return _up(x - 1, y);
}
int _down(int x, int y) // 下
{
if (a[x][y] == '#')
{
return 0;
}
if (a[x][y] == 'G')
{
return 1 + _down(x + 1, y);
}
return _down(x + 1, y);
}
int _left(int x, int y) // 左
{
if (a[x][y] == '#')
{
return 0;
}
if (a[x][y] == 'G')
{
return 1 + _left(x, y - 1);
}
return _left(x, y - 1);
}
int _right(int x, int y) // 右
{
if (a[x][y] == '#')
{
return 0;
}
if (a[x][y] == 'G')
{
return 1 + _right(x, y + 1);
}
return _right(x, y + 1);
}
int doit(int x, int y) // 统计炸到的僵尸数目
{
return _up(x - 1, y) + _down(x + 1, y) + _left(x, y - 1) + _right(x, y + 1);
}
void bfs(void) // 广度优先搜索求最大值
{
int i, r, c;
if (q.empty()) // 队列空则停止
{
return;
}
res = max(res, doit(q.front().x, q.front().y)); // res存储最大值
for (i = 0; i < 4; i++) // 四个方向扩展
{
r = q.front().x + dx[i];
c = q.front().y + dy[i];
if ((a[r][c] == '.') && (!v[r][c]))
{
_next.x = r;
_next.y = c;
v[r][c] = true;
q.push(_next);
}
}
q.pop();
bfs();
return;
}
int main() // 主函数
{
int n, m, i, j, x, y;
cin >> n >> m >> x >> y;
for (i = 1; i <= n; i++) // 读入地图
{
for (j = 1; j <= m; j++)
{
cin >> a[i][j];
}
}
_next.x = x;
_next.y = y;
v[x][y] = true;
q.push(_next);
bfs();
cout << res << endl; // 输出结果
return 0;
}#include <iostream>
#inc