poj 2704 Pascal's Travels 记忆化dfs或dp
记忆化dfs
当搜索到一个位置,如果这个位置的下面已经被搜索过了,则直接返回它的值
View Code
#include <stdio.h>
#include <string.h>
int n;
__int64 vis[36][36];
char board[36][36];
__int64 dfs(int x,int y)
{
int i;
if(x==n-1&&y==n-1)return 1;
if(board[x][y]=='0')return 0;
if(vis[x][y])return vis[x][y];
if(x+board[x][y]-'0'<n)
vis[x][y]+=dfs(x+board[x][y]-'0',y);
if(y+board[x][y]-'0'<n)
vis[x][y]+=dfs(x,y+board[x][y]-'0');
return vis[x][y];
}
int main()
{
int i,j;
while (scanf("%d",&n)!=EOF)
{
if(n==-1)break;
for (i=0;i<n;i++)
scanf("%s",board[i]);
memset(vis,0,sizeof(vis));
printf("%lld\n",dfs(0,0));
}
return 0;
}
dp
View Code
#include <stdio.h>
#include <string.h>
__int64 vis[50][50];
char board[50][50];
int main()
{
int i,j,n;
while (scanf("%d",&n)!=EOF)
{
if(n==-1)break;
for (i=0;i<n;i++)
scanf("%s",board[i]);
memset(vis,0,sizeof(vis));
vis[0][0]=1;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
if(board[i][j]=='0')continue;
vis[i+board[i][j]-'0'][j]+=vis[i][j];
vis[i][j+board[i][j]-'0']+=vis[i][j];
}
}
printf("%lld\n",vis[n-1][n-1]);
}
return 0;
}