hdu 1026
http://acm.hdu.edu.cn/showproblem.php?pid=1026
题目意思 从左上角走到右下角需要的最短时间
输出要走的路径
解决这个题目的话就是BFS
具体的思路写在注释里边了
#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
struct node
{
int x,y;
int step;
//优先队列里边的排序规则
friend bool operator<(node n1,node n2)
{
return n2.step<n1.step;
}
};
int dir[4][2]={0,1, 1,0, 0,-1, -1,0};
int map[111][111];
int flag[111][111];
int blood[111][111];
int n,m;
int roarNumber;
int judge(int x,int y)
{
//判断边界条件
if(x<0 || x>=n || y<0 || y>=m) return 1;
if(map[x][y]==-1) return 1;
return 0;
}
int BFS()
{
//定义一个优先队列
priority_queue<node>q;
node cur,next;
int i;
//初始坐标点(0,0)
cur.x=0;
cur.y=0;
cur.step=0;
map[0][0]=-1;
q.push(cur);
while(!q.empty())
{
cur=q.top();
q.pop();
//走到右下角
if(cur.x==n-1 && cur.y==m-1)
return cur.step;
//四个方向广搜
for(i=0;i<4;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
//如果这个点不符合条件的话 直接跳过下边的步骤进行循环
if(judge(next.x,next.y))
continue;
//记录下一个位置的步数 map里边存放的是这个点需要停留的时间
next.step=cur.step+1+map[next.x][next.y];
//记录从哪个方向来到这个点的
flag[next.x][next.y]=i+1;
// 标记一下这个点走过了
map[next.x][next.y]=-1;
q.push(next);
}
}
return -1;
}
void road(int x,int y)
{
//用递归的方式查找
int next_x,next_y;
//右下角的点最后会是0
if(flag[x][y]==0)
return ;
next_x=x-dir[flag[x][y]-1][0];
next_y=y-dir[flag[x][y]-1][1];
road(next_x,next_y);
printf("%ds:(%d,%d)->(%d,%d)\n",roarNumber++,next_x,next_y,x,y);
while(blood[x][y]--)
{
//输出停留的时间
printf("%ds:FIGHT AT (%d,%d)\n",roarNumber++,x,y);
}
}
int main()
{
char str[111];
int i,l;
int ans;
while(scanf("%d%d",&n,&m)!=-1)
{
memset(map,0,sizeof(map));
memset(flag,0,sizeof(flag));
memset(blood,0,sizeof(blood));
for(i=0;i<n;i++)
{
scanf("%s",str);
for(l=0;str[l];l++)
{
if(str[l]=='.')
{
//不需要停留
map[i][l]=0;
}
else
{
if(str[l]=='X')
{
//不能走
map[i][l]=-1;
}
else
{
//需要停留
map[i][l]=blood[i][l]=str[l]-'0';
}
}
}
}
ans=BFS();
if(ans==-1)
{
printf("God please help our poor hero.\n");
}
else
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
roarNumber=1;
road(n-1,m-1);
}
printf("FINISH\n");
}
return 0;
}