http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=9§ionid=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;
}
本文介绍了一种解决HDU竞赛中特定问题的高效算法,仅使用一次广度优先搜索(BFS)即可实现0ms的解决方案。该方法通过避免重复状态检查,并利用优先队列进行优化,有效地解决了游戏问题。
613

被折叠的 条评论
为什么被折叠?



