洛谷 P1825 [USACO11OPEN] Corn Maze S

#include<iostream>
#include<queue>
using namespace std;
const int N = 350;
struct Pos {
	int x, y;
	int dis;		//将距离定义到结构体队列中
};
const int dx[4] = { 0,1,0,-1 };
const int dy[4] = { 1,0,-1,0 };

bool vis[N][N];
char g[N][N];
int n, m;
queue<Pos>q;
int ans;

void transport(int &x,int &y) {					//单独将传送写成一个函数
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (g[i][j] == g[x][y] && (i != x || j != y)) {		//寻找与当前传送门匹配的传送门,且搜到的相同字母不能是和当前点相同
				x = i;
				y = j;
				return;
			}
		}
	}
}

int bfs(int ix, int iy) {

	q.push({ ix,iy ,0});
	vis[ix][iy] = true;

	while (q.size()) {
		auto t = q.front();
		q.pop();

		if (g[t.x][t.y] == '=') {		//如果已经走到了终点,那么就直接返回这个点的距离
			return t.dis;
		}

		if (g[t.x][t.y] >= 'A' && g[t.x][t.y] <= 'Z') {		//如果这个点是传送门
			transport(t.x, t.y);
		}

		for (int i = 0; i < 4; i++) {
			int xx = t.x + dx[i], yy = t.y + dy[i];
			if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && vis[xx][yy] == false && g[xx][yy] != '#') {
				vis[xx][yy] = true;
				q.push({ xx,yy,t.dis + 1 });
			}
		}

	}
}

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

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> g[i][j];
		}
	}

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (g[i][j] == '@') {		//找到起点
				ans = bfs(i, j);
				break;
			}
		}
	}

	cout << ans;
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值