poj3984

简单题

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
using namespace std;

#define maxn 10

struct Point
{
int x, y;
}q[maxn
* maxn], stk[maxn * maxn];

int map[maxn][maxn];
int cost[maxn][maxn];
int from[maxn][maxn];
int dir[4][2] =
{
{
1, 0 },
{
0, 1 },
{
-1, 0 },
{
0, -1 } };

bool ok(Point &a)
{
if (a.x < 0 || a.y < 0 || a.x >= 5 || a.y >= 5)
return false;
return !map[a.x][a.y] && (cost[a.x][a.y] == -1);
}

int main()
{
//freopen("t.txt", "r", stdin);
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
scanf(
"%d", &map[i][j]);
int l = 0;
int r = 1;
q[
0].x = 0;
q[
0].y = 0;
memset(cost,
-1, sizeof(cost));
cost[
0][0] = 0;
while (l != r)
{
for (int i = 0; i < 4; i++)
{
Point p;
p.x
= q[l].x + dir[i][0];
p.y
= q[l].y + dir[i][1];
if (ok(p))
{
q[r
++] = p;
from[p.x][p.y]
= i;
cost[p.x][p.y]
= cost[q[l].x][q[l].y] + 1;
}
}
l
++;
}
int top = 0;
Point a;
a.x
= 4;
a.y
= 4;
int t;
while (!(a.x == 0 && a.y == 0))
{
stk[top
++] = a;
t
= from[a.x][a.y];
a.x
-= dir[t][0];
a.y
-= dir[t][1];
}
printf(
"(0, 0)\n");
while (top--)
printf(
"(%d, %d)\n", stk[top].x, stk[top].y);
return 0;
}

posted @ 2011-07-03 21:39  undefined2024  阅读(718)  评论(0)    收藏  举报