|Tyvj|BFS|P1117 拯救ice-cream

22 篇文章 0 订阅

http://tyvj.cn/p/1117

做BFS,但是不能走到#时直接加2,这样得不出最优时间,需要把#当做两个格子来走,即走完#将他更改为^,入队时仍然入head的x,y,然后在没有加上坐标之前判断是不是^,是的话把它更改为通路“.”,再次入队。


参考代码

#include<cstdio>
struct sb {
	int x,y,time;
};
sb hs[10000];
int pre[10000];
const int dx[4] = {1,0,-1,0},
		  dy[4] = {0,1,0,-1};
int t,x,y;
int mx,my,sx,sy;
char map[30][30];
void init () {
	scanf("%d%d%d\n", &t, &y, &x);
	int i,j;
	for (i=0;i<x;i++) {
		gets(map[i]);
		for (j=0;j<y;j++) {
			if (map[i][j]=='m') {
				mx = i, my = j;
			}
			if (map[i][j]=='s') {
				sx = i, sy = j;
			}
		}
	}
}
void bfs() {
	int i;
	int head=0, tail=1;
	hs[1].x = sx, hs[1].y = sy, hs[1].time = 0; pre[0]=0;
	do {
		head++;
		if (map[hs[head].x][hs[head].y] == '^') {
			tail++;
			hs[tail].x = hs[head].x;
			hs[tail].y = hs[head].y;
			hs[tail].time = hs[head].time+1;
			map[hs[head].x][hs[head].y] = '.';
			pre[tail] = head;
		} else 
		for (i=0;i<4;i++) {
			int cx = hs[head].x + dx[i], cy = hs[head].y + dy[i];
			if (cx >= 0 && cy >=0 && cx < x && cy < y) {
				if (map[cx][cy] == '.') {
					tail++;
					hs[tail].x = cx;
					hs[tail].y = cy;
					hs[tail].time = hs[head].time+1;
					map[cx][cy] = 'o';
					pre[tail] = head;
				}
				if (map[cx][cy] == '#') {
					tail++;
					hs[tail].x = cx;
					hs[tail].y = cy;
					hs[tail].time = hs[head].time+1;
					map[cx][cy] = '^';
					pre[tail] = head;
				}
				if (map[cx][cy] == 'm') {
					if (hs[head].time+1<t) {
						printf("%d\n", hs[head].time+1);
					} else printf("55555\n");
					return;
				}
			}
		} 
	} while(head<tail);
}
int main() {
	init();
	bfs();
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值