| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 77763 | Accepted: 28905 | 
Description
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
Input
Output
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
Source
当搜索某个坐标位置处某个状态时(这个状态是最优状态),顺便把其他坐标的最优状态也搜出来了,这样搜索下一个坐标最优状态时,当到达一个位置最优状态已经求出来时就返回,也就是搜过的就不用再搜了。
比如本题,step[i][j] ,定义为 从i,j位置最远可以滑多少步(不包括自己),在搜一遍的时候,把搜到的位置所最优状态(最远可以滑多少步)也同时搜出来了。
寻找全局最优时,搜索每一个坐标,当该坐标如果已经被搜索过了(在之前坐标位置处被搜索),那么就直接返回该坐标的最优状态。从而找到全局最优状态。
代码:
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn=105;
int mp[maxn][maxn];
int step[maxn][maxn];
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
int n,m;
void input()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        cin>>mp[i][j];
}
bool ok(int x,int y)
{
    if(x>=1&&x<=n&&y>=1&&y<=m)
        return true;
    return false;
}
int dfs(int x,int y)
{
    if(step[x][y])
        return step[x][y];
    for(int i=0;i<4;i++)
    {
        int newx=x+dx[i];
        int newy=y+dy[i];
        if(ok(newx,newy)&&mp[newx][newy]<mp[x][y])
        {
            int temp=dfs(newx,newy)+1;//四个方向找最长
            if(temp>step[x][y])
                step[x][y]=temp;
        }
    }
    return step[x][y];
}
void solve()
{
    int ans=-1;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
    {
        int temp=dfs(i,j);
        if(ans<temp)
            ans=temp;
    }
    cout<<ans+1<<endl;
}
int main()
{
    memset(step,0,sizeof(step));
    input();
    solve();
    return 0;
}
原文地址:http://blog.csdn.net/sr_19930829/article/details/40320379