hdu1254 推箱子



http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=9&sectionid=2&problemid=3

网上很多文章都说是bfs+dfs,其实一次bfs就够了

无非就是小人往四个方向走,碰到箱子就推,碰不到拉倒,4维数组查重,(可以用优先队列优化)-->(感觉不用优先队列会出问题)

当然不是说bfs+dfs不行,毕竟优化是竞赛的重点...但一个bfs不是更好理解么,而且还是0ms...


#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;

struct Point{
	int step,pr,pc,br,bc;
	bool operator <(const Point& b)const{
		return step>b.step;
	}
}s,e;


int N,M;
int G[7][7];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};

/*void print(Point s){
	printf("step: %d\n",s.step);
	for(int i=0;i<N;i++,printf("\n"))
		for(int j=0;j<M;j++)
			if(i==s.pr&&j==s.pc) printf("%d ",4);
			else if(i==s.br&&j==s.bc) printf("%d ",2);
			else if(i==e.br&&j==e.bc) printf("%d ",3);
			else printf("%d ",G[i][j]);
}*/


bool vis[7][7][7][7];

bool checkFail(Point &ns){//人出界,人撞墙,箱出界,箱撞墙
	if(ns.pr<0||ns.pr>=N||ns.pc<0||ns.pc>=M||ns.br<0||ns.br>=N||ns.bc<0||ns.bc>=M) return true;
	if(G[ns.pr][ns.pc]||G[ns.br][ns.bc]) return true;
	if(vis[ns.pr][ns.pc][ns.br][ns.bc]) return true;
	return false;
}

bool move(Point &ns,Point &s,int dr,int dc){
	ns=s;
	ns.pr+=dr,ns.pc+=dc;
	
	if(checkFail(ns)) return false;//人出界或人撞墙 
	
	if(ns.pr==ns.br&&ns.pc==ns.bc){//人推箱 
		ns.br+=dr,ns.bc+=dc;
		ns.step+=1;
		if(checkFail(ns)) return false;//箱出界或撞墙
		return true;
	}else return true;//不推箱 
}


int bfs()
{
	memset(vis,0,sizeof vis);
	
	Point ns;
	
	priority_queue<Point> q;
	vis[s.pr][s.pc][s.br][s.bc]=true;
	q.push(s);
	
	//print(s);
	
	while(!q.empty()){
		s=q.top();q.pop();
		//print(s);
		
		if(s.br==e.br&&s.bc==e.bc) return s.step;
		
		for(int i=0;i<4;i++){
			if(move(ns,s,dir[i][0],dir[i][1])){
				if(ns.br==e.br&&ns.bc==e.bc) return ns.step;
				else{
					vis[ns.pr][ns.pc][ns.br][ns.bc]=true;
					q.push(ns);	
				}
			}
		}
		
	}
	
	return -1;
}

void SOLVE()
{
	printf("%d\n",bfs());
}

void INPUT()
{
	scanf("%d%d",&N,&M);
	
	memset(G,0,sizeof G);
	for(int i=0;i<N;i++)
		for(int j=0;j<M;j++){
			scanf("%d",&G[i][j]);
			if(G[i][j]==2) G[i][j]=0,s.br=i,s.bc=j;
			else if(G[i][j]==3) G[i][j]=0,e.br=i,e.bc=j;
			else if(G[i][j]==4) G[i][j]=0,s.pr=i,s.pc=j;
		}
	
	s.step=0;
}

void MAIN()
{
	int T;
	scanf("%d",&T);
	while(T--)
		INPUT(),SOLVE();
}

int main()
{
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	MAIN();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值