Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 109886 | Accepted: 41839 |
Description
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。
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
具體思路:
這個題咋一看思路很簡單,就是從每個點深搜,通過比較求出最大距離
這樣會逾時,原因就是對于從一個點開始深搜求一個最長的距離,必然它所搜到的點肯定也要求從目前點深搜的最短距離,
就會造成一個點多次深搜求最長距離的這樣一個局面
為了解決這個問題,我們在搜一個點的時候,可以記錄下目前點所能到達的最遠距離,這樣再搜其他點的時候,再遇到之前的
點就可以直接用那個點所能到達的最短距離了
import java.util.Arrays;
import java.util.Scanner;
public class Main3 {
static final int max=105;
static int dp[][]=new int [max][max];
static int map[][]=new int [max][max];
static int r,c;
static int dirx[]={1,-1,0,0};
static int diry[]={0,0,1,-1};
public static int dfs(int x,int y){
if(dp[x][y]!=-1) return dp[x][y];//如果目前點已經求出最遠距離,直接用就可以
int t=1;
for(int i=0;i<4;i++){
int xx=x+dirx[i];
int yy=y+diry[i];
if(xx<0||xx>=r||yy<0||yy>=c) continue;
if(map[x][y]>map[xx][yy])
t=Math.max(t, dfs(xx,yy)+1);//向四個方向深搜,求出目前點能到達的最遠距離
}
return dp[x][y]=t;//把目前點的所能到達的最遠距離記錄下來并傳回
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
r=scan.nextInt();
c=scan.nextInt();
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
map[i][j]=scan.nextInt();
}
}
for(int i=0;i<max;i++)
Arrays.fill(dp[i], -1);
int ans=0;
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
ans=Math.max(ans, dfs(i,j));
System.out.println(ans);
}
}