没有什么难度,就是要用优先级队列,需要重载小于运算符。不用优先级队列不能过!!!!!!!
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;
int dir[4][2] = {0 , 1 , 0 , -1 , 1 , 0 , -1 , 0};
struct pos
{
int x , y;
int flag;
};
struct point
{
int x,y;
int step;
int flag;
pos line[1000];
int times;
friend bool operator< (point n1, point n2)
{
return n1.step > n2.step;
}
};
void Bfs(char Map[102][102] , int visit[102][102] , int m , int n)
{
if(Map[0][0] == 'X')
{
printf("God please help our poor hero.\n");
printf("FINISH\n");
return ;
}
point temp;
pos result[1000];
temp.x = 0;
temp.y = 0;
if(Map[0][0] != '.')
{
temp.flag = Map[0][0] - '0';
temp.step = Map[0][0] - '0';
}
else
{
temp.flag = 0;
temp.step = 0;
}
temp.times = 0;
visit[0][0] = 1;
temp.line[0].x = temp.x;
temp.line[0].y = temp.y;
temp.line[0].flag = temp.flag;
priority_queue <point>Q;
Q.push(temp);
int sum = 9999999;
int num = 0;
while(!Q.empty())
{
temp = Q.top();
Q.pop();
if(temp.x == m-1 && temp.y == n - 1)
{
sum = temp.step;
for(int i = 0 ; i <= temp.times ; i ++ )
{
result[i] = temp.line[i];
}
num = temp.times;
break;
}
for(int i = 0 ; i < 4 ; i ++ )
{
point cur;
cur.x = temp.x + dir[i][0];
cur.y = temp.y + dir[i][1];
if(cur.x >=0 && cur.x < m && cur.y >=0 && cur.y < n && !visit[cur.x][cur.y] && Map[cur.x][cur.y] != 'X')
{
if(Map[cur.x][cur.y] == '.')
{
cur.step = temp.step + 1;
cur.flag = 0;
}
else
{
cur.step = temp.step + Map[cur.x][cur.y] - '0' + 1;
cur.flag = Map[cur.x][cur.y] - '0';
}
cur.times = temp.times + 1;
int i;
for(i = 0 ; i <= temp.times ; i ++ )
cur.line[i] = temp.line[i];
cur.line[i].x = cur.x;
cur.line[i].y = cur.y;
cur.line[i].flag = cur.flag;
Q.push(cur);
visit[cur.x][cur.y] = 1;
}
}
}
// if(num == 0 && )
if(sum != 9999999)
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n" , sum);
int k = 1;
for(int i = 0 ; i < num ; i ++ )
{
if(result[i].flag == 0)
{
printf("%ds:(%d,%d)->(%d,%d)\n" , k ++ , result[i].x , result[i].y , result[i+1].x , result[i+1].y );
}
else
{
while(result[i].flag -- )
{
printf("%ds:FIGHT AT (%d,%d)\n" , k ++ ,result[i].x , result[i].y);
}
if(i + 1 <= num) printf("%ds:(%d,%d)->(%d,%d)\n" , k ++ , result[i].x , result[i].y , result[i+1].x , result[i+1].y );
}
}
if(result[num].flag)
{
while(result[num].flag -- )
{
printf("%ds:FIGHT AT (%d,%d)\n" , k ++ ,result[num].x , result[num].y);
}
}
}
else
{
printf("God please help our poor hero.\n");
}
printf("FINISH\n");
}
int main()
{
int m , n;
while(scanf("%d%d", &m , &n) != EOF)
{
char Map[102][102];
int visit[102][102];
memset(visit , 0 ,sizeof(visit));
for(int i = 0 ; i < m ; i ++ )
{
cin>>Map[i];
}
Bfs(Map , visit , m , n);
}
return 0;
}