依然是经典搜索,+了记忆化,速度快了不少.即在bfs的过程中,只有当当前点的hp>目标点的hp时,才走这一步.
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int m, n;
int Map[101][101];
int dp[101][101];
int sx, sy, ex, ey;

typedef struct
{
int x,y;
int hp;
int cnt;
}Point;

int main()
{
int i, j;
Point s, t, tt;
while (cin >> n >> m)
{
if(n==0 && m==0)
break;
for (i=0; i<m; ++i)
{
for (j=0; j<n; ++j)
{
cin >> Map[i][j];
if(Map[i][j] == 2)
sx = i, sy = j;
if (Map[i][j] == 3)
ex = i, ey = j;
}
}
bool flag = false;
memset(dp, 0, sizeof(dp));
s.x = sx, s.y = sy, s.cnt = 0, s.hp = 6, dp[sx][sy] = 6;
queue<Point> mq;
mq.push(s);
while (!mq.empty())
{
t = mq.front();
mq.pop();

if(t.x==ex && t.y==ey && t.hp>0)
{
flag = true;
break;
}
if(t.hp <= 1)
continue;
for (i=0; i<4; ++i)
{
int x = t.x + dir[i][0];
int y = t.y + dir[i][1];

if(x>=0&&x<m && y>=0&&y<n && Map[x][y]!=0)
{
if(dp[x][y] < dp[t.x][t.y])
{
if(Map[x][y] == 4)
dp[x][y] = 6;
else
dp[x][y] = dp[t.x][t.y]-1;
tt.x = x;
tt.y = y;
tt.hp = dp[x][y];
tt.cnt = t.cnt+1;
if(tt.hp > 0)
mq.push(tt);
}
}
}
}
if(!flag)
cout << "-1";
else
cout << t.cnt;
cout << endl;

}
return 0;
}






















































































