hdu 1428 bfs+记忆化搜索
#include <iostream>
#include <queue>
using namespace std;
int map[55][55], n;
int dist[55][55];
__int64 dp[55][55];
const int INF = INT_MAX;
int dir[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
struct Node
{
int x, y;
};
queue <Node> q;
void bfs()
{
while (!q.empty())
{
q.pop();
}
Node first, next;
first.x = n, first.y = n;
dist[n][n] = map[n][n];
q.push(first);
while (!q.empty())
{
first = q.front();
q.pop();
int i;
for (i = 0; i < 4; ++i)
{
next.x = first.x + dir[i][0];
next.y = first.y + dir[i][1];
if (next.x > 0 && next.x <= n && next.y > 0 && next.y <= n)
{
if (map[next.x][next.y] + dist[first.x][first.y] < dist[next.x][next.y])
{
dist[next.x][next.y] = map[next.x][next.y] + dist[first.x][first.y];
q.push(next);
}
}
}
}
}
__int64 Search(int x, int y)
{
if (dp[x][y] != -1)
{
return dp[x][y];
}
else if (x == n && y == n)
{
return 1;
}
else
{
int i, fx, fy;
__int64 sum = 0;
for (i = 0; i < 4; ++i)
{
fx = x + dir[i][0];
fy = y + dir[i][1];
if (fx > 0 && fx <= n && fy > 0 && fy <= n && dist[fx][fy] < dist[x][y])
{
sum += Search(fx, fy);
}
}
dp[x][y] = sum;
return sum;
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
int i, j;
for (i = 1; i <= n; ++i)
{
for (j = 1; j <= n; ++j)
{
dist[i][j] = INF;
scanf("%d", &map[i][j]);
}
}
bfs();
memset(dp, -1, sizeof(dp));
Search(1,1);
printf("%I64d\n", dp[1][1]);
}
return 0;
}
#include <queue>
using namespace std;
int map[55][55], n;
int dist[55][55];
__int64 dp[55][55];
const int INF = INT_MAX;
int dir[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
struct Node
{
int x, y;
};
queue <Node> q;
void bfs()
{
while (!q.empty())
{
q.pop();
}
Node first, next;
first.x = n, first.y = n;
dist[n][n] = map[n][n];
q.push(first);
while (!q.empty())
{
first = q.front();
q.pop();
int i;
for (i = 0; i < 4; ++i)
{
next.x = first.x + dir[i][0];
next.y = first.y + dir[i][1];
if (next.x > 0 && next.x <= n && next.y > 0 && next.y <= n)
{
if (map[next.x][next.y] + dist[first.x][first.y] < dist[next.x][next.y])
{
dist[next.x][next.y] = map[next.x][next.y] + dist[first.x][first.y];
q.push(next);
}
}
}
}
}
__int64 Search(int x, int y)
{
if (dp[x][y] != -1)
{
return dp[x][y];
}
else if (x == n && y == n)
{
return 1;
}
else
{
int i, fx, fy;
__int64 sum = 0;
for (i = 0; i < 4; ++i)
{
fx = x + dir[i][0];
fy = y + dir[i][1];
if (fx > 0 && fx <= n && fy > 0 && fy <= n && dist[fx][fy] < dist[x][y])
{
sum += Search(fx, fy);
}
}
dp[x][y] = sum;
return sum;
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
int i, j;
for (i = 1; i <= n; ++i)
{
for (j = 1; j <= n; ++j)
{
dist[i][j] = INF;
scanf("%d", &map[i][j]);
}
}
bfs();
memset(dp, -1, sizeof(dp));
Search(1,1);
printf("%I64d\n", dp[1][1]);
}
return 0;
}