AcWing 901. 滑雪(記憶化搜索)

題目鏈接:點擊這裏

在這裏插入圖片描述
在這裏插入圖片描述
dfs求出從每個點出發所能到達的最遠距離,然後遍歷起點取最大值。

在搜索過程中,爲了防止重複計算,開一個數組記錄搜索結果。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 310;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

int r, c;
int a[N][N], f[N][N];

int dfs(int x, int y)
{
    int &v = f[x][y];       // 使用引用,簡化代碼
    
    if(v)   return f[x][y];
    
    v = 1;
    for(int i = 0; i < 4; ++i)
    {
        int tx = x + dx[i], ty = y + dy[i];
        if(tx >= 1 && tx <= r && ty >= 1 && ty <= c && a[tx][ty] < a[x][y])
		{
		    v = max(v, dfs(tx, ty) + 1);
		}
    }
    
    return v;
}

int main()
{
    scanf("%d%d", &r, &c);
    for(int i = 1; i <= r; ++i)
        for(int j = 1; j <= c; ++j)
            scanf("%d", &a[i][j]);
    
    int ans = -1e9;
    for(int i = 1; i <= r; ++i)
        for(int j = 1; j <= c; ++j)
            ans = max(ans, dfs(i, j));
    
    printf("%d\n", ans);
    
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章