Ski dp memory search

Given to a matrix of R rows and C columns, showing a rectangular grid ski.

Dot matrix j-th column indicates the height of the i-th row j-th column of the i-th row region ski.

Starting from a person in a ski area, each unit may slide a distance in the vertical and horizontal directions in any one.

Of course, a person can slide into an adjacent area of ​​the premise is the height of the area below the height of the area of ​​their current location.

A matrix is ​​given below by way of example:

1 2 3 4 5

16 17 18 19 6

15 24 25 20 7

14 23 22 21 8

13 12 11 10 9

In a given matrix, a viable sliding track is 24-17-2-1.

In a given matrix, the longest glide trajectory 25-24-23- ... -3-2-1, along the way after a total of 25 regions.

Now given you a two-dimensional matrix represents the height of the regional ski resorts, you find the longest ski tracks in the ski area can be completed, and the output of its length (available through the maximum number of area).
Input Format

The first line contains two integers R and C.

Next R rows, each row contains C integers, represent a full two-dimensional matrix.
Output Format

Output an integer representing the maximum achievable length of the ski.
data range

1≤R, C≤300
,
0 ≦ matrix integer ≤10000

Sample input:

5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

Sample output:

25

#include<bits/stdc++.h>
using namespace std;
const   int N=330;
int a[N][N];
int f[N][N];
    int n,m;
    int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
void dfs(int x,int y)
{
    f[x][y]=1;
    for(int i=0;i<4;i++)
    {
        int tx=x+dx[i];
        int ty=y+dy[i];
        if(tx<0||ty<0||tx>=n||ty>=m||a[tx][ty]>=a[x][y])    continue;
        if(f[tx][ty]==-1)  dfs(tx,ty);
      f[x][y]=max(f[x][y],f[tx][ty]+1);
    }
}
int main()
{
    int ans=0;
    memset(f,-1,sizeof f);
    cin>>n>>m;
    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++)
    cin>>a[i][j];
    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++)
    if(f[i][j]==-1)
    {
        dfs(i,j);
        ans=max(ans,f[i][j]);
    }
    cout<<ans<<endl;
    return 0;
}
Published 165 original articles · won praise 8 · views 2483

Guess you like

Origin blog.csdn.net/qq_45961321/article/details/104859391