您的位置:首页 > 其它

HDU1026 Ignatius and the Princess I

2015-10-07 22:56 190 查看
解题思路:打印路径是关键,细节处理见代码。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 105;
char mapp[maxn][maxn];
int q[maxn*maxn*4][2]; //队列,刚开始没有乘以4,结果RE了
//dp[i][j]表示走到坐标(i,j)时所用的时间
//pre[x][y]存储当前点的前一个点在队列中的位置
int pre[maxn][maxn], dp[maxn][maxn], n, m, f, r, tmp, t;
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};

void bfs()
{
f = 0, r = 1; //f为头指针,r为尾指针
q[0][0] = 0, q[0][1] = 0, dp[0][0] = 0;

while(f != r)
{
int x = q[f][0], y = q[f][1];
tmp = f; //与32行对应
f ++; //出队列

for(int i = 0; i < 4; i++)
{
int xx = x + dir[i][0];
int yy = y + dir[i][1];
int tt = dp[x][y] + 1;
if(xx < 0 || xx >= n || yy < 0 || yy >= m || mapp[xx][yy] == 'X') continue;
//如果当前点之前到达过,并且所用的时间小于或等于当前点,进行下一次循环。
if(dp[xx][yy] != -1 && dp[xx][yy] <= tt) continue;
if(mapp[xx][yy] != '.') tt += mapp[xx][yy] - '0'; //遇到怪兽,原地扁他
pre[xx][yy] = tmp, q[r][0] = xx, q[r][1] = yy, dp[xx][yy] = tt, r ++;
}
}
return ;
}

int Print(int x,int y)
{
int k = pre[x][y];

if(pre[x][y] == -1) return 0; //不能走,则返回;
Print(q[k][0], q[k][1]); //好好体会这里的递归。

printf("%ds:(%d,%d)->(%d,%d)\n", t++, q[k][0], q[k][1], x, y);
if(mapp[x][y] != '.') //说明是怪兽,原地痛打
for(int i = 0; i < mapp[x][y] - '0'; i++) //数字多大就打多久
printf("%ds:FIGHT AT (%d,%d)\n", t++, x, y);
return 0;
}

int main()
{
while(~scanf("%d %d", &n, &m))
{
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) scanf(" %c", &mapp[i][j]);

memset(dp, -1, sizeof(dp)); //都初始化为没有访问过
memset(pre, -1, sizeof(pre));
bfs();

//说明走不到这一点
if(dp[n-1][m-1] == -1) printf("God please help our poor hero.\n");
else
{
printf("It takes %d seconds to reach the target position,"
" let me show you the way.\n", dp[n-1][m-1]);
t = 1;
Print(n - 1,m - 1); //打印路径。
}
printf("FINISH\n");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: