HDU 1072 Nightmare (BFS 状态的设定:参考了别人的代码)

来源:互联网 发布:程序员技术移民新西兰 编辑:程序博客网 时间:2024/05/16 15:34
#include<iostream>
#include<cstdio>
#include<queue>
#include<memory.h>
using namespace std;
int si,sj,di,dj,T,n,m,flag;
int maze[10][10],hash[10][10];
int move[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node{
int x,y,t,step;
}begin;
inline int IN(int x,int y)
{
if(x<=0||x>n||y<=0||y>m)
return 0;
else
return 1;
}
void BFS()
{
queue<node>q;
node temp,cur;
int i;
q.push(begin);
hash[begin.x][begin.y]=6;
while(!q.empty())
{
cur=q.front();
q.pop();
// printf("%d %d %d %d***\n",cur.x,cur.y,cur.t,cur.step);
for(i=0;i<4;i++)
{
temp.x=cur.x+move[i][0];
temp.y=cur.y+move[i][1];
if(!IN(temp.x,temp.y))  continue;//不是return
if(maze[temp.x][temp.y]!=0)
{
temp.t=cur.t-1;
temp.step=cur.step+1;
if(maze[temp.x][temp.y]==4)
temp.t=6;
                if(maze[temp.x][temp.y]==3)
{
       flag=1;
       cout<<temp.step<<endl;
return;//不是break
}
if(temp.t>1&&hash[temp.x][temp.y]<temp.t)
{
hash[temp.x][temp.y]=temp.t;
q.push(temp);//位置开始放错了
}
//printf("%d %d %d %d***\n",temp.x,temp.y,temp.t,temp.step);
}
}//***************for
}//*************while
}
int main()
{
scanf("%d",&T);
while(T--)
{
int i,j;
scanf("%d %d",&n,&m);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
//scanf("%d",&maze[i][j]);
cin>>maze[i][j];
                if(maze[i][j]==2)
{ begin.x=i;begin.y=j;}
}
/*for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
printf("%d",maze[i][j]);
cout<<endl;
}*/
    begin.t=6, begin.step=0,flag=0;
memset(hash,0,sizeof(hash));
BFS();
if(!flag)
cout<<"-1\n";
}
return 0;
}