hdu 1026 Ignatius and the Princess I
普通广搜而已,只不过队列是优先队列,以时间为key
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
#define MAXSIZE 110
struct qnode
{
int x,y,time;
bool operator<(const qnode &e) const
{
//最小堆
return e.time<time;
}
};
priority_queue <qnode> que;
struct path_node
{
int prex,prey;
};
path_node path[MAXSIZE][MAXSIZE];
int seconds,N,M,dir[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
char maze[MAXSIZE][MAXSIZE];
bool visited[MAXSIZE][MAXSIZE];
bool bfs()
{
while( !que.empty() ) que.pop();
qnode cur,next;
cur.x=N-1;
cur.y=M-1;
if(maze[N-1][M-1]=='.') cur.time=0;
else cur.time=maze[N-1][M-1]-'0';
que.push(cur);
visited[N-1][M-1]=true;
path[N-1][M-1].prex=path[N-1][M-1].prey=-1;
int i,j,k;
while(!que.empty())
{
cur=que.top();
if(cur.x==0 && cur.y==0)
{
seconds=cur.time;
return true;
}
que.pop();
for(k=0; k<4; k++)
{
i=cur.x+dir[k][0];
j=cur.y+dir[k][1];
if(i<0 || i>=N || j<0 || j>=M || visited[i][j] || maze[i][j]=='X') continue;
if(maze[i][j]=='.')
{
next.x=i;
next.y=j;
next.time=cur.time+1;
que.push(next);
}
else
{
next.x=i;
next.y=j;
next.time=cur.time+1 + maze[i][j]-'0';
que.push(next);
}
path[i][j].prex=cur.x;
path[i][j].prey=cur.y;
visited[i][j]=true;
}
}
return false;
}
void printpath()
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",seconds);
int i=0,j=0,k,ti,tj;
seconds=1;
if(maze[0][0]!='.')
{
k=maze[0][0]-'0';
while(k--)
{
printf("%ds:FIGHT AT (%d,%d)\n",seconds,i,j);
seconds++;
}
}
while(path[i][j].prex != -1)
{
ti=i;
tj=j;
i=path[ti][tj].prex;
j=path[ti][tj].prey;
printf("%ds:(%d,%d)->(%d,%d)\n",seconds,ti,tj,i,j);
if(maze[i][j]!='.')
{
k=maze[i][j]-'0';
while(k--)
{
seconds++;
printf("%ds:FIGHT AT (%d,%d)\n",seconds,i,j);
}
}
seconds++;
}
printf("FINISH\n");
}
int main()
{
while(scanf("%d%d",&N,&M)!=EOF)
{
getchar();
int i,j;
for(i=0; i<N; i++)
{
for(j=0; j<M; j++)
scanf("%c",&maze[i][j]);
getchar();
}
memset(visited,0,sizeof(visited));
if( bfs() ) printpath();
else printf("God please help our poor hero.\nFINISH\n");
}
return 0;
}
浙公网安备 33010602011771号