您的位置:首页 > 其它

hdu_1072_nightmare_BFS_用时间来限定

2014-12-19 21:50 447 查看
代码来自于别人,自己写怎么都AC不过,明早一早要看的内容:

//HDU1072 Nightmare
//http://acm.hdu.edu.cn/showproblem.php?pid=1072
//这道题和别的bfs不一样的是它有一个还原点的设置,所以在标记用过的点时
//不能单单以坐标为标准,还要有这一点的时间
#include<iostream>
#include<queue>
using namespace std;
int dir[][2]={0,1,1,0,0,-1,-1,0}; //4个方向
struct node
{
int x;
int y;
int time;//剩余的时间
int step;//走过的步数
}begin;
int n,m,i,j;
int map[10][10]; //地图
int mark[10][10];//标记时间
void bfs();
int main()
{
int cases;
scanf("%d",&cases);
while(cases--)
{
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
scanf("%d",&map[i][j]);
if(map[i][j]==2) //找出起点
{
begin.x=i;
begin.y=j;
begin.time=6;
begin.step=0;
}
mark[i][j] = 0 ;//标记初始化为0
}
bfs();
}
return 0;
}
void bfs()
{
queue<node>q;
q.push(begin);  //起点入队
mark[begin.x][begin.y] = begin.time ;
node p,temp;
while(!q.empty()) //队列为空还没找到就是-1了
{
p=q.front();
q.pop();
for(i=0;i<4;i++)
{
temp=p;
temp.x+=dir[i][0];
temp.y+=dir[i][1];
if(temp.x>n||temp.x<0||temp.y>m||temp.y<0||map[temp.x][temp.y]==0)   //边界判断
continue;
temp.step++; //步数加1
temp.time--; //剩余时间减1
if(map[temp.x][temp.y]==3) //出口
{
printf("%d/n",temp.step);
return ;  //退出函数
}
else if ( map[temp.x][temp.y] == 4 )   //还原点
{
temp.time = 6 ;
}
if( temp.time > 1 && mark[temp.x][temp.y] < temp.time ) //标记该点当剩余时间更大时就标记
{
mark[temp.x][temp.y] = temp.time;
q.push(temp) ;
}
}
}
printf("%d/n",-1);//队列为空还没找到就是-1了
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: