洛谷_P1825 [USACO11OPEN]Corn Maze S(尚贤)

【题目】:https://www.luogu.com.cn/problem/P1825

#include <cstdio>
#include <queue>
#include <vector>
#define SIZE 300 + 5
using namespace std;
struct node2{
	int x, y, t;
	node2() {
	}
	node2(const int &xx, const int &yy, const int &tt) {
		x = xx, y = yy, t = tt;
	}
};
char map[SIZE][SIZE];
bool vis[SIZE][SIZE];
int n, m, walk[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

int bfs(const int &x, const int &y);

int main() {
	freopen("cpp.in", "r", stdin);
	freopen("cpp.out", "w", stdout);
	int a, b;
	scanf("%d%d", &n, &m);
	for (int i = 0; i < n; ++i) {
		scanf("%s", &map[i]);
		for (int j = 0; j < m; ++j) {
			if (map[i][j] == '@') {
				a = i, b = j;
			}
		}
	}
	printf("%d", bfs(a, b));
	return 0;
}


int bfs(const int &x, const int &y) {
	queue<node2> q;
	q.push(node2(x, y, 0));
	vis[x][y] = true;
	while (!q.empty()) {
		if (map[q.front().x][q.front().y] >= 'A' && map[q.front().x][q.front().y] <= 'Z') {
//			printf("#### %d %d %d\n", q.front().x, q.front().y, q.front().t);
			for (int i = 0; i < n; ++i) {
				for (int j = 0; j < m; ++j) {
					if (!(i == q.front().x && j == q.front().y) && map[i][j] == map[q.front().x][q.front().y]/* && !vis[i][j]*/) {
						q.front() = node2(i, j, q.front().t);
//						printf("@@@@ %d %d %d\n", q.front().x, q.front().y, q.front().t);
//						vis[i][j] = true;
						i = n, j = m;
					}
				}
			}
		}
		node2 now = q.front();
//		printf("%d %d %d\n", q.front().x, q.front().y, q.front().t);
		q.pop();
		for (int i = 0; i < 4; ++i) {
			int nx = now.x + walk[i][0];
			int ny = now.y + walk[i][1];
			if (nx >= 0 && ny >= 0 && nx < n && ny < m && !vis[nx][ny] && map[nx][ny] != '#') {
				if (map[nx][ny] == '=') {
					return now.t + 1;
				}
				q.push(node2(nx, ny, now.t + 1));
				vis[nx][ny] = true;
			}
		}
	}
	return -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值