题意:一张地图上面有六种地形,每种地形消耗不同的行动能力,给出初始位置,求出可以到达的地方
思路:宽度优先遍历
错误:最开始用深度优先遍历,一直超时。后来在直接在ma数组上改的那个版本里,判断每一个地方的代价的函数里面少写了当地形为“ * ”的时候,不过我也不知道为什么会出来这种情况,还有为什么要把" * "看成是" . " 。在下面判断坐标范围的时候神奇的把纵坐标的最大值打成了n,一直没发现卡了好长时间。
代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
char ma[105][105];
char ans[105][105];
int m,n,mv;
int yx,yy;
int hashk[105][105];
struct Pos
{
int x;
int y;
int e;
};
queue<Pos> ss;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
char getch()
{
char a;
a=getchar();
while(a!='.'&&a!='Y'&&a!='T'&&a!='R'&&a!='#'&&a!='E'&&a!='P')a=getchar();
return a;
}
int rest(char A)
{
if(A=='.')return 1;
else if(A=='T')return 2;
else if(A=='R')return 3;
else if(A=='#')return 120000;//no
else if(A=='E')return 120000;//no
else if(A=='P')return 1;//no
}
Pos tmp;
Pos now;
void bfs(int x,int y)
{
tmp.x=x;
tmp.y=y;
tmp.e=mv;
ss.push(tmp);
hashk[tmp.x][tmp.y]=mv;
while(!ss.empty())
{
tmp=ss.front();
ss.pop();
if(tmp.e<=0)continue;
for(int i=0;i<4;++i)
{
now.x=tmp.x+dir[i][0];
now.y=tmp.y+dir[i][1];
if(now.x<0)continue;
if(now.x>=n)continue;
if(now.y<0)continue;
if(now.y>=m)continue;
int &xx=now.x;
int &yy=now.y;
if(ma[xx][yy]=='#')continue;
else if(ma[xx][yy]=='E')continue;
else if(ma[xx][yy]=='Y')continue;
now.e=tmp.e-rest(ma[now.x][now.y]);
if(now.e>=0)
if(xx-1>=0&&ma[xx-1][yy]=='E')now.e=0;
else if(xx+1<n&&ma[xx+1][yy]=='E')now.e=0;
else if(yy+1<m&&ma[xx][yy+1]=='E')now.e=0;
else if(yy-1>=0&&ma[xx][yy-1]=='E')now.e=0;
if(now.e>=0&&ma[xx][yy]!='P')ans[xx][yy]='*';
hashk[now.x][now.y]=now.e;
ss.push(now);
}
}
}
}
int main(){
// freopen("data.txt","r",stdin);
int T;
scanf("%d",&T);
while(T)
{
T--;
scanf("%d%d%d",&n,&m,&mv);
memset(hashk,-1,sizeof(hashk));
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
{
ma[i][j]=getch();
ans[i][j]=ma[i][j];
if(ma[i][j]=='Y'){
yx=i;
yy=j;
}
}
}
bfs(yx,yy);
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
{
printf("%c",ans[i][j]);
}
printf("\n");
}
printf("\n");
}
return 0;
}