$\tt WA on \#34$ 求助!样例全过!
查看原帖
$\tt WA on \#34$ 求助!样例全过!
998662
xk2013楼主2024/6/23 12:05
#include <cstdio>
#include <cstring>
#include <queue>

struct Node
{
	int x;
	int y;
	int t;
};

char map[505][505];
bool vis[505][505];
int h, w, fx, fy, sx, sy;
const int dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
bool ans = false;
void bfs(int fx, int fy, int sx, int sy);

int main(void)
{
	scanf("%d %d", &h, &w);
	
	for (int i = 0; i < h; i++)
	{
		scanf("%s", map[i]);
		
		for (int j = 0; j < w; j++)
		{
			if (map[i][j] == 's')
			{
				fx = i;
				fy = j;
			}
			else if (map[i][j] == 'g')
			{
				sx = i;
				sy = j;
			}
		}
	}

	bfs(fx, fy, sx, sy);
	memset(vis, 0, sizeof vis);
	bfs(sx, sy, fx, fy);
	
	printf(ans ? "YES\n" : "NO\n");
	return 0;
}

void bfs(int fx, int fy, int sx, int sy)
{
	std::queue <Node> q;
	q.push(Node{fx, fy, 0});
	
	while (!q.empty())
	{
		Node f = q.front();
		q.pop();
		
		if (f.x == sx && f.y == sy && f.t <= 2)
		{
			ans = true;
			return;
		}
		
		for (int i = 0; i < 4; i++)
		{
			int tx = f.x + dir[i][0];
			int ty = f.y + dir[i][1];
			
			if (0 <= tx && tx < h && 0 <= ty && ty < w && !vis[tx][ty])
			{
				if (map[tx][ty] == '#' && f.t < 2)
				{
					vis[tx][ty] = true;
					q.push(Node{tx, ty, f.t + 1});
				}
				else if (map[tx][ty] != '#')
				{
					vis[tx][ty] = true;
					q.push(Node{tx, ty, f.t});
				}
			}
		}
	}
}
2024/6/23 12:05
加载中...