/*
题意:给个二维数组,'.'可以走,'X'不可走,'1-9'代表在此消耗的时间
输出记录从(0,0)到(n-1,m-1)的耗时最小值
YY: :从(n-1,m-1)到(0,0)逆向BFS,记录上一点,直接输出最优序列
*/
#include <iostream>
#include <queue>
using namespace std;
const int MAX = 99999999;
int n,m;
struct zu{
char c;
int num,x,y,qianx,qiany;
}map[110][110];
int dir[4][2]={{-1,0},{0,-1},{1,0},{0,1}};
void Print()
{
int x, y, a, b, num, i;
num = 1;
if(map[0][0].num != MAX){
printf("It takes %d seconds to reach the target position, let me show you the way.\n",map[0][0].num);
x =0; y =0;
while(x != n - 1 || y != m - 1){
a = map[x][y].qianx;
b = map[x][y].qiany;
if(map[x][y].c >= '1' && map[x][y].c <= '9')
{
for(i = 0;i < map[x][y].c - '0'; ++i)
printf("%ds:FIGHT AT (%d,%d)\n", num++, x, y);
}
printf("%ds:(%d,%d)->(%d,%d)\n", num++, x, y, a, b);
x = a; y = b;
}
if(map[x][y].c >= '1' && map[x][y].c <= '9'){
for(i = 0;i < map[x][y].c - '0'; ++i)
printf("%ds:FIGHT AT (%d,%d)\n", num++, x, y);
}
printf("FINISH\n");
}
else{
printf("God please help our poor hero.\nFINISH\n");
}
}
void bfs()
{
int i,bu;
char temp_c;
struct zu a;
queue<struct zu> Q;
//
map[n-1][m-1].num = 0;
if(map[n-1][m-1].c >= '1' && map[n-1][m-1].c <= '9')
map[n-1][m-1].num = map[n-1][m-1].c - '0';
else if(map[n-1][m-1].c == '.')
bu = 1;
if(map[n-1][m-1].c != 'X')
Q.push(map[n-1][m-1]);
//
while(!Q.empty())
{
a = Q.front();
for(i = 0; i < 4; ++i)
{
int addx,addy;// 为后面代码简洁
addx = dir[i][0];
addy = dir[i][1];
if(map[a.x + addx][a.y + addy].c == 'X'
|| a.y + addy >= m || a.x + addx < 0 || a.y + addy < 0 || a.x + addx >= n)
continue;
temp_c = map[a.x + addx][a.y + addy].c;
if(temp_c == '.')
bu = a.num;
else if(temp_c >= '1' && temp_c <= '9')
bu = a.num + temp_c - '0';
if(bu +1 < map[a.x + addx][a.y + addy].num) // 当出现比现在小的状态时更新
{
map[a.x + addx][a.y + addy].num = bu + 1;
map[a.x + addx][a.y + addy].qianx = a.x;
map[a.x + addx][a.y + addy].qiany = a.y;
Q.push(map[a.x + addx][a.y + addy]);
}
}
Q.pop();
}
Print();
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
for(i = 0;i < n; ++i){
for(j = 0;j < m; ++j){
scanf("%c", &map[i][j].c);
map[i][j].num = MAX;
map[i][j].x = i;
map[i][j].y = j;
map[i][j].qianx = -1;
map[i][j].qiany = -1;
}
getchar();
}
bfs();
}
return 0;
}