1. 程式人生 > 實用技巧 >POJ 1088--滑雪

POJ 1088--滑雪

題目連結:http://poj.org/problem?id=1088

題目描述:

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更長。事實上,這是最長的一條。

輸入:

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

輸出:

輸出最長區域的長度。


題解:

本題可以使用記憶化搜尋,設定一個step[x][y]

1.step[x][y]表示從x,y開始向下滑的時候最長的步數。

2.step[x][y]表示相應的位置是否被訪問過,等於初始值0則為未訪問,就對step[x][y]進行搜尋;

 大於0就是搜尋過了,且數值本身就是向下滑的最長步數,就不用繼續搜尋了。

遞迴搜尋的時候 step[x][y] =max(“向上”,“向下”,“向左”,“向右”)+1;


程式碼:

package t1;
import java.util.Scanner;

public class Main {
	static int r,c;
	static int mp[][] = new int[102][102];
	static int step[][] = new int[102][102];
	
	public static int f(int x,int y) {//返回節點x,y的最長路徑
		if(step[x][y]!=0) {
			return step[x][y];	//直接返回,不用繼續搜尋了
		}
		int rt = 0;
		//向四個方向搜尋
		if(y<c && mp[x][y]>mp[x][y+1])
			rt = Math.max(rt, f(x,y+1));
		if(x<r && mp[x][y]>mp[x+1][y])
			rt = Math.max(rt, f(x+1,y));
		if(y>1 && mp[x][y]>mp[x][y-1])
			rt = Math.max(rt, f(x,y-1));
		if(x>1 && mp[x][y]>mp[x-1][y])
			rt = Math.max(rt, f(x-1,y));
		return step[x][y] = rt+1;
	}
	
    public static void main(String[] args) {
    	Scanner cin  = new Scanner(System.in);
    	r = cin.nextInt();
    	c = cin.nextInt();
    	for(int i=1;i<=r;i++)
    		for(int j=1;j<=c;j++)
    			mp[i][j] = cin.nextInt();
    	int ans = 0;
    	for(int i=1;i<=r;i++) {
    		for(int j=1;j<=c;j++) {
    			if(step[i][j]==0) {
    				ans = Math.max(ans, f(i,j));
    			}
    		}
    	}
    	System.out.println(ans);
    }
}