题解 AT4529 【Grid 1】

Update:2021.1.4 LaTeX\, \, \, \, \, \large \LaTeX 炸了

本题明显可以用 DFS,并且不会 TLE

但会 RE\color{purple} \text{RE}

附上 DFS 代码:

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

string a[1005];
int H, W;
const int Mod = 1e9 + 7;
long long cnt = 0;

void dfs(const int& x, const int& y, long long cnts = 0)
{
    if(a[x][y] == '#' || !(x >= 1 && x <= H && y >= 1 && y <= W)) return ;
    dfs(x, y + 1);
    dfs(x + 1, y);
    cnts++;
    if(x == H && y == W) cnt += cnts;
    cnt %= Mod;
}

int main()
{
    int m = 1, n = 1;
    cin >> H >> W;
    for(register int i = 1; i <= H; i++)
    {
        for(register int j = 1; j <= W; j++) cin >> a[i][j];
    }
    dfs(m, n);
    cout << cnt % Mod << endl;
    return 0;
}

递归多次导致栈溢出,RE\color{purple} \text{RE}

这种题目我们更可以用 DP 做。

先给个转移方程:

dpij={(dpij1+dpi1j)mod(109+7)aij#0aij=#1{i=1,j=1}\large {dp_{i}}_{j} = \begin{cases} ({dp_i}_{j-1}+{dp_{i-1}}_j) \mod(10^9+7) & {a_i}_j \not = \# \\0 \,\,\,\,\,\,\, {a_i}_j = \# \\1 \,\,\,\,\,\,\, \{i = 1, \,\, j = 1\}\end{cases}

那么这个转移方程怎么推出来的呢?

因为是往下或往右,所以对于每个 dpij\large dp_{i_j},往下是 dpi1j\large {dp_{i-1}}_{j},也就是列标不变,而往右是 dpij\large {dp_i}_j,行标不变,而我们是逆着推,就是从上面来或从左侧来,因此分别是 dpi1j\large {dp_{i-1}}_jdpij1\large {dp_i}_{j-1}

时间复杂度 O(HW)\large O(HW)

代码:

#include <iostream>
using namespace std;

char a[1005][1005];
long long dp[1005][1005];
int H, W;
const int Mod = 1e9 + 7;
long long cnt = 0;

int main()
{
    cin >> H >> W;
    for(register int i = 1; i <= H; i++)
    {
        for(register int j = 1; j <= W; j++) cin >> a[i][j];
    }
    dp[1][1] = 1;
    for(register int i = 1; i <= H; i++)
    {
        for(register int j = 1; j <= W; j++)
        {
            if(a[i][j] == '.')
            {
                dp[i][j] += dp[i][j - 1];
                dp[i][j] += dp[i - 1][j];
                dp[i][j] %= Mod;
            }
        }
    }
    cout << dp[H][W] << endl;
    return 0;
}

要注意的是本题不能用 string 做,无论是 DP 还是 DFS,都会 RE\color{purple} \text{RE},猜测是由于 string 内存溢出吧$。

posted @   HappyBobb  阅读(2)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示