最短路径+记忆化搜索
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int INF=0x7ffffff;
int n;
int map[55][55];
int shi[55][55];
__int64 hasd[55][55];
int dis[4][2]={1,0,0,1,-1,0,0,-1};
struct point
{
int x;
int y;
};
void bfs() //记录每点到终点最短距离,记录在shi[i][j]中
{
int i,tt;
queue<point> q;
point cur,next;
cur.x=n-1;
cur.y=n-1;
shi[n-1][n-1]=map[n-1][n-1];
q.push(cur);
while(!q.empty())
{
cur=q.front();
q.pop();
for(i=0;i<4;i++)
{
next.x=cur.x+dis[i][0];
next.y=cur.y+dis[i][1];
if(next.x>=0&&next.x<n&&next.y>=0&&next.y<n)
{
tt=shi[cur.x][cur.y]+map[next.x][next.y];
if(shi[next.x][next.y]>tt)
{
shi[next.x][next.y]=tt;
q.push(next);
}
}
}
}
}
__int64 dfs(int x1,int y1) //记录每点到终点符合条件的个数,记录在hasd[i][j]中
{
int x2,y2;
if(hasd[x1][y1]>0)
return hasd[x1][y1];
if(x1==n-1&&y1==n-1)
return 1;
for(int i=0;i<4;i++)
{
x2=x1+dis[i][0];
y2=y1+dis[i][1];
if(x2>=0&&x2<n&&y2>=0&&y2<n)
{
if(shi[x2][y2]<shi[x1][y1])
hasd[x1][y1]+=dfs(x2,y2);
}
}
return hasd[x1][y1];
}
int main()
{
while(scanf("%d",&n)==1)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&map[i][j]);
shi[i][j]=INF;
}
}
memset(hasd,0,sizeof(hasd));
bfs();
__int64 ans=dfs(0,0);
#if 0
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%I64d ",hasd[i][j]);
}
printf("\n");
}
#endif
printf("%I64d\n",hasd[0][0]);
}
return 0;
}