您的位置:首页 > 其它

hdu 1026 bfs(数组模拟,路径输出)

2015-04-27 22:01 337 查看
题意:

给一张图,求从左上角到右下角的最短路径。

图上的数字代表一个怪物,杀掉怪物用的时间。

解析:

路径输出改了一晚,开始用指针去指,然后就全指乱了。

然后改成了数组模拟。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1

using namespace std;
const int maxn = 100 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-6;
const double pi = acos(-1.0);
const double ee = exp(1.0);

int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int n, m;
char g[maxn][maxn];
int pre[maxn][maxn];
int dp[maxn][maxn];
int q[maxn * maxn * 20][2];

void bfs(int sx, int sy, int ex, int ey)
{
int front = 0, rear = 1, parent;
memset(dp, -1, sizeof(dp));
memset(pre, -1, sizeof(pre));
dp[sx][sy] = 0;
q[0][0] = sx;
q[0][1] = sy;
while (front != rear)
{
int x = q[front][0];
int y = q[front][1];
parent = front;
front++;
for (int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (0 <= nx && nx < n && 0 <= ny && ny < m && g[nx][ny] != 'X')
{
int cnt = dp[x][y] + 1;
if (g[nx][ny] != '.')
cnt += g[nx][ny] - '0';
if (dp[nx][ny] == -1 || cnt < dp[nx][ny])
{
dp[nx][ny] = cnt;
pre[nx][ny] = parent;
q[rear][0] = nx;
q[rear][1] = ny;
rear++;
}
}
}
}
}

int printPath(int x, int y)
{
int pos = pre[x][y];
if (pos == -1)
return 0;
int t = printPath(q[pos][0], q[pos][1]);
printf ("%ds:(%d,%d)->(%d,%d)\n", ++t, q[pos][0], q[pos][1], x, y);
if (g[x][y] != '.')
{
for (int i = 0; i < g[x][y] - '0'; i++)
{
printf ("%ds:FIGHT AT (%d,%d)\n", ++t, x, y);
}
}
return t;
}

int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
{
scanf("%s", g[i]);
}
bfs(0, 0, n - 1, m - 1);
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]);
printPath(n-1, m-1);
}
printf("FINISH\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: