本文主要是介绍hdu 1254 BFS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
// 这道题还没过,不知道哪里错了,希望有人帮我Debug
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int n,m,x1,y1,x2,y2,x3,y3;
int vist[8][8][8][8],map[8][8];
struct node
{int x,y,j,k,t;
};bool check(int x, int y)
{if( x>=1 && x<=m && y>=1 && y<=n )return 1;return 0;
}int bfs()
{queue<node> v;node a,b;int i;a.x=x3,a.y=y3,a.j=x1,a.k=y1,a.t=0;v.push(a);while(!v.empty()){a=v.front(); v.pop();// printf("%d %d %d %d %d\n",a.x,a.y,a.j,a.k,a.t);if( a.j==x2 && a.k==y2 )return a.t;for(i=0;i<4;i++){if(i==0 && check(a.x-1,a.y) && map[a.x-1][a.y]==0 ) //shang{if( !(a.x-1==a.j&&a.y==a.k) && vist[a.x-1][a.y][a.j][a.k]==0 ){ b=a; b.x--; v.push(b); vist[a.x-1][a.y][a.j][a.k]=1; }else if( a.x-1==a.j && a.y==a.k && check(a.x-2,a.y) && vist[a.x-1][a.y][a.j-1][a.k]==0 && map[a.x-2][a.y]==0 ){ b=a; b.x--; b.j--; b.t++; v.push(b); vist[a.x-1][a.y][a.j-1][a.k]=1; }}else if(i==1 && check(a.x+1,a.y) && map[a.x+1][a.y]==0 ) //xia{if( !(a.x+1==a.j&&a.y==a.k) && vist[a.x+1][a.y][a.j][a.k]==0 ){ b=a; b.x++; v.push(b); vist[a.x+1][a.y][a.j][a.k]=1; }else if( a.x+1==a.j && a.y==a.k && check(a.x+2,a.y) && vist[a.x+1][a.y][a.j+1][a.k]==0 && map[a.x+2][a.y]==0 ){ b=a; b.x++; b.j++; b.t++; v.push(b); vist[a.x+1][a.y][a.j+1][a.k]=1; }}else if(i==2 && check(a.x,a.y-1) && map[a.x][a.y-1]==0 ) //zuo{if( !(a.x==a.j&&a.y-1==a.k) && vist[a.x][a.y-1][a.j][a.k]==0 ){ b=a; b.y--; v.push(b); vist[a.x][a.y-1][a.j][a.k]=1; }else if( a.x==a.j && a.y-1==a.k && check(a.x,a.y-2) && vist[a.x][a.y-1][a.j][a.k-1]==0 && map[a.x][a.y-2]==0 ){ b=a; b.y--; b.k--; b.t++; v.push(b); vist[a.x][a.y-1][a.j][a.k-1]=1; }}else if(i==3 && check(a.x,a.y+1) && map[a.x][a.y+1]==0 ) //you{if( !(a.x==a.j&&a.y+1==a.k) && vist[a.x][a.y+1][a.j][a.k]==0 ){ b=a; b.y++; v.push(b); vist[a.x][a.y+1][a.j][a.k]=1; }else if( a.x==a.j && a.y+1==a.k && check(a.x,a.y+2) && vist[a.x][a.y+1][a.j][a.k+1]==0 && map[a.x][a.y+2]==0 ){ b=a; b.y++; b.k++; b.t++; v.push(b); vist[a.x][a.y+1][a.j][a.k+1]=1; }}}}return -1;
}int main()
{freopen("in","r",stdin);freopen("out","w",stdout);int cas,ans,i,r;scanf("%d",&cas);while(cas--){memset(vist,0,sizeof(vist));memset(map,0,sizeof(map));scanf("%d%d",&m,&n);for(i=1;i<=m;i++)for(r=1;r<=n;r++){scanf("%d",&map[i][r]);if(map[i][r]==2){x1=i; y1=r; map[i][r]=0;}else if(map[i][r]==3){x2=i; y2=r; map[i][r]=0;}else if(map[i][r]==4){x3=i; y3=r; map[i][r]=0;}}vist[x3][y3][x1][y1]=1;ans=bfs();printf("%d\n",ans);}return 0;
}
这篇关于hdu 1254 BFS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!