AcWing 901. ski (memory search)

Topic links: Click here

Here Insert Picture Description
Here Insert Picture Description
dfs obtained from each point can reach the farthest distance, and then take the maximum traversal start.

In the search process, in order to prevent double-counting, an array of open searches.

#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;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105032444