poj 1088 滑雪 記憶化搜索

滑雪
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 79919   Accepted: 29747

Descriptionios

Michael 喜歡滑雪百這並不奇怪, 由於滑雪的確很刺激。但是爲了得到速度,滑的區域必須向下傾斜,並且當你滑到坡底,你不得再也不次走上坡或者等待升降機來載你。Michael想知道載一個 區域中最長底滑坡。區域由一個二維數組給出。數組的每一個數字表明點的高度。下面是一個例子
 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

一我的能夠從某個點滑向上下左右相鄰四個點之一,當且僅當高度減少。在上面的例子中,一條可滑行的滑坡爲24-17-16-1。固然25-24-23-...-3-2-1更長。事實上,這是最長的一條。

Input數組

輸入的第一行表示區域的行數R和列數C(1 <= R,C <= 100)。下面是R行,每行有C個整數,表明高度h,0<=h<=10000。

Outputide

輸出最長區域的長度。

Sample Inputspa

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 Outputxml

25
題解:跑一發DFS,記憶化搜索一下就好
#include<iostream>
using namespace std;
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int n,m;
int map[102][102];
int dp[102][102];
int dfs(int x,int y)
{
    //cout <<x << " " << y << endl;
    int tx,ty,i;
    if(dp[x][y])                         //當已經搜索過期就返回
        return dp[x][y];
    for(i =  0;i < 4;i++)
    {
        tx = x + dir[i][0] , ty = y + dir[i][1];
        if(tx >= 0 && tx < n && ty >= 0 && ty < m && map[tx][ty] < map[x][y])//搜索+ 狀態轉移方程
        {
            int temp = dfs(tx,ty); //遞歸的出口有兩個1.在11行;2.在16行
            if(dp[x][y] <= temp) //i=0時比較dfs(x+1, y);i=1時比較dfs(x, y+1);i=2時比較dfs(x-1, y);i=3時比較dfs(x, y-1)
            {   
                dp[x][y] = temp+1;    
            }
        }
    }
    return dp[x][y];
}
int main()
{
    int i,j,t;
    while(cin >> n >> m)
    {
        for(i =0 ;i < n;i++)
        {
            for(j = 0;j < m;j++)
            {
                cin >> map[i][j];
                dp[i][j] = 0;
            }
        }
        int max = -1;
        for(i = 0 ;i < n;i++)
        {
            for(j = 0;j < m;j++)
            {
                t = dfs(i,j);
                if(max < t)
                {
                    max = t;
                }
            }
        }
        cout <<max + 1 << endl;
    }
    return 0;
}
相關文章
相關標籤/搜索