bfs,
strcut Status { int x, y, rest, step; }; 入队列,进行扩展直到到达目的地,vis[][][]标记剩下某能量达到某位置是否有过
代码:
#include <cstring>
#include <queue>
#include <cstdio>
using namespace std;
#define N 102
int r, c, d, ans;
char data[N][N];
bool vis[N][N][N];
struct Item
{
int x, y, rest, step;
Item() {}
Item(int _x, int _y, int _r, int _s): x(_x), y (_y), rest(_r), step(_s) {}
bool legal() {return x>0 && x<=r && y>0 && y<=c && data[x][y]=='P' && !vis[x][y][rest];}
bool destinate() {return x==r && y==c;}
void visit() {vis[x][y][rest] = true;}
};
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int bfs()
{
if (r == 1 && c == 1) return 0;
vis[1][1][d] = true;
queue <Item> Q;
Q.push(Item(1,1,d,0));
Item cur, nxt;
while (!Q.empty())
{
cur = Q.front();
Q.pop();
for (int i = 0; i < 4; ++ i)
{
nxt = Item(cur.x+dir[i][0], cur.y+dir[i][1], cur.rest, cur.step+1);
if (nxt.legal())
{
nxt.visit();
Q.push(nxt);
if (nxt.destinate()) return nxt.step;
}
for (int j = 2; j <= cur.rest; ++ j)
{
nxt = Item(cur.x+j*dir[i][0], cur.y+j*dir[i][1], cur.rest-j, cur.step+1);
if (nxt.legal())
{
nxt.visit();
Q.push(nxt);
if (nxt.destinate()) return nxt.step;
}
}
}
}
return -1;
}
int main()
{
while (~scanf("%d %d %d", &r, &c, &d))
{
memset(vis, false, sizeof(vis));
for (int i = 1; i <= r; ++ i)
scanf("%s", data[i]+1);
ans = bfs();
if (ans == -1) printf("impossible\n");
else printf("%d\n", ans);
}
}