bfs

#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef pair<int, int>PII;
const int N = 110;
int n, m;
int a, b;//起点
int c, d;//终点
char map[N][N];
int dist[N][N];
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
//PII pre[N][N];

void bfs(int x, int y)
{
	//int ret = 0;
	queue<PII>q;
	q.push({ x,y });

	dist[x][y] = 0;
	map[x][y] = '#';
	while (q.size())
	{
		auto u = q.front();
		q.pop();

		if (map[u.first][u.second] == 'a')
		{
			c = u.first, d = u.second;
			//return ret;
			return;
		}
		bool flag = false;
		for (int i = 0; i < 4; i++)
		{
			int nx = u.first + dx[i]; int ny = u.second + dy[i];
			if (nx < 0 || nx >= n || ny < 0 || ny >= m)continue;
			if (map[nx][ny] == '#' || dist[nx][ny] != -1)continue;

			if (map[nx][ny] == '.')
			{
				flag = true;
				break;
			}
			//int cmp = dist[u.first][u.second];
			//if (map[nx][ny] == 'x')
			//{
			//	dist[nx][ny] = cmp + 2;
			//}
			//else dist[nx][ny] = cmp + 1;

			////pre[a][b] = u;
			//q.push({ nx,ny });
		}
		
			for (int i = 0; i < 4; i++)
			{
				int nx = u.first + dx[i]; int ny = u.second + dy[i];
				if (nx < 0 || nx >= n || ny < 0 || ny >= m)continue;
				if (map[nx][ny] == '#' || dist[nx][ny] != -1)continue;

				int cmp = dist[u.first][u.second];
				if (map[nx][ny] == 'x')
				{
					if(flag)continue;
					dist[nx][ny] = cmp + 2;
				}
				else dist[nx][ny] = cmp + 1;

				//pre[a][b] = u;
				q.push({ nx,ny });
			}
		
		
		
	}
}

//void husu(int x, int y)
//{
//	if (x == a && y == b)return;
//	if (map[x][y] == 'x')tim += 2;
//	else tim += 1;
//	PII p = pre[x][y];
//	husu(p.first, p.second);
//	
//}

int main() {
	cin >> n >> m;

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> map[i][j];
			if (map[i][j] == 'r')
			{
				a = i, b = j;
			}
			dist[i][j] = -1;
		}
	}
	bfs(a, b);
	//husu(c, d);

	if (dist[c][d] == -1)cout << -1 << endl;
	else cout << dist[c][d] << endl;
}
posted @ 2024-11-28 17:36  某朝  阅读(4)  评论(0编辑  收藏  举报