社区讨论

BFS 88分求助

P2199最后的迷宫参与者 1已保存回复 0

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
0 条
当前快照
1 份
快照标识符
@lrviliw8
此快照首次捕获于
2024/01/27 11:30
2 年前
此快照最后确认于
2024/01/27 11:30
2 年前
查看原帖
CPP
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int dx[8] = {-1,1,0,0,1,1,-1,-1};
int dy[8] = {0,0,-1,1,1,-1,1,-1};
struct node
{
	int x,y;
};
int n,m,x1,x2,y1,y2;
char c[1010][1010];
bool flag[1010][1010];
int dis[1010][1010];
int bfs()
{
	queue<node> q;
	memset(flag,0,sizeof(flag));
	memset(dis,-1,sizeof(dis));
	for(int i = 0;i <= 7;i++)
	{
		int nx = x2,ny = y2;
		while(nx >= 1 && nx <= n && ny >= 1 && ny <= m && c[nx][ny] == 'O')
		{
			flag[nx][ny] = 1;
			nx += dx[i];
			ny += dy[i];
		}
	}
	q.push({x1,y1});
	dis[x1][y1] = 0;
	while(!q.empty())
	{
		int xx = q.front().x,yy = q.front().y;
		q.pop();
		if(flag[xx][yy] == 1) return dis[xx][yy];
		for(int i = 0;i <= 3;i++)
		{
			int nx = xx + dx[i],ny = yy + dy[i];
			if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && c[nx][ny] == 'O' && dis[nx][ny] == -1)
			{
				q.push({nx,ny});
				dis[nx][ny] = dis[xx][yy] + 1;
			}
		}
	}
	return -1;
}
int main()
{
	cin >> n >> m;
	for(int i = 1;i <= n;i++)
	{
		for(int j = 1;j <= m;j++)
		{
			cin >> c[i][j];
		}
	}
	while(true)
	{
		cin >> x2 >> y2 >> x1 >> y1;
		if(x1 == 0) break;
		int ans = bfs();
		if(ans == -1) cout << "Poor Harry" << endl;
		else cout << ans << endl;
	}
	return 0;
}

回复

0 条回复,欢迎继续交流。

正在加载回复...