hdoj 1028/poj 2704 Pascal's Travels(记忆化搜索||dp)

2021-01-22 12:51:15 浏览数 (1)

题目链接

题意

有个小球,只能向右边或下边滚动,而且它下一步滚动的步数是它在当前点上的数字,如果是0表示进入一个死胡同。求它从左上角到右下角到路径数目。

注意, 题目给了提示了,要用64位的整数。

记忆化搜索方法

代码语言:javascript复制
#include <stdio.h>
#include <string.h>
#define ll __int64
int n;
ll vis[36][36];
char board[36][36];

ll dfs(int x,int y)
{
    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()
{
    while (scanf("%d",&n)!=EOF)
    {
        if(n == -1)
            break;
        for (int i = 0; i < n; i  )
            scanf("%s",board[i]);
        memset(vis, 0, sizeof(vis));
        printf("%I64dn", dfs(0,0));
    }
    return 0;
}

dp方法

代码语言:javascript复制
#include <stdio.h>
#include <string.h>
#define ll __int64

ll 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("%I64dn", vis[n-1][n-1]);
    }
    return 0;
}

0 人点赞