上课的时候,想找一道水题随便写写玩玩,没想到WA了,之后我改了一天也没找到错误在哪,没办法只好推倒重写了,莫名A了,我还是太菜了。。。
题意:给你一张地图,'.'表示可以走的路,'X'表示不可以走的墙,'1'-'9'表示有怪兽,走到有怪兽的格子必须先杀死怪兽才能继续走。起点是(0,0),终点是(n-1,m-1)。如果可以去,就输出话费最小时间的路径,如果不可以就输出那段英文。
解法:宽搜,只要用结构体记录每个点的源点即可,然后递归输出,很裸的题。
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define pi acos(-1.0)
#define eps 1e-8
using namespace std;
const int maxnode = 1005;
int nums = 0;
int n, m;
struct step
{
int x, y;
int need;
}maps[maxnode][maxnode];
struct Point
{
int x, y, s;
Point(int x=0, int y=0, int s=0): x(x),y(y),s(s) {}
bool operator==(const Point& p) const {return x==p.x&&y==p.y;}
bool operator<(const Point& p) const {return s>p.s;}
};
bool vis[maxnode][maxnode];
int fx[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
bool bfs()
{
priority_queue<Point> q;//用优先队列,优先处理s(时间)少的点。
maps[0][0].x = maps[0][0].y = -1;
q.push(Point(0,0));
memset(vis,true,sizeof vis);vis[0][0] = false;
while(!q.empty())
{
Point tmp = q.top(); q.pop();
if(tmp==Point(n-1,m-1))
{
nums = tmp.s;
return true;
}
for(int i = 0 ; i < 4 ; ++ i)
{
int x = tmp.x + fx[i][0];
int y = tmp.y + fx[i][1];
int s = tmp.s;
int need = maps[x][y].need;
if(x<n&&x>=0&&y<m&&y>=0&&maps[x][y].need>=0&&vis[x][y])//是否为可走点
{
vis[x][y] = false;
maps[x][y].x=tmp.x;
maps[x][y].y=tmp.y;
q.push(Point(x,y,s+need+1));
}
}
}
return false;
}
int tt;
void ddd(int x, int y)//递归打印
{
if((maps[x][y].x==-1&&maps[x][y].y==-1)) return;
ddd(maps[x][y].x, maps[x][y].y);
printf("%ds:(%d,%d)->(%d,%d)\n",tt++,maps[x][y].x, maps[x][y].y,x,y);
for(int i = 0 ; i < maps[x][y].need ; ++ i)
{
printf("%ds:FIGHT AT (%d,%d)\n",tt++,x,y);
}
}
void print()// 输出函数
{
if(bfs())
{
int x = n-1, y = m-1;tt = 1;
printf("It takes %d seconds to reach the target position, let me show you the way.\n",nums);
ddd(x,y);
}
else
{
printf("God please help our poor hero.\n");
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(~scanf("%d%d", &n, &m))
{
char s[1001];
for(int i = 0 ; i < n ; ++ i)
{
scanf("%s", s);
for(int j = 0 ; j < m ; ++ j)
{
if(s[j]=='.')
{
maps[i][j].need = 0;
}
else if(s[j]=='X')
{
maps[i][j].need = -1;
}
else
{
maps[i][j].need = s[j]-'0';
}
}
}
print();
printf("FINISH\n");
}
return 0;
}