pku1088

使用DFS算法和备忘录的方式,减少迭代次数。

import java.util.Scanner;


public class Main {
	public static int[][]result;
	public static void main(String[] args) {
	       Scanner cin=new Scanner(System.in);
	       int r=cin.nextInt();
	       int c=cin.nextInt();
	       int [][]heights=new int[r][c];
	       result=new int[r][c];
	       for(int i=0;i<r;i++){
	    	   for(int j=0;j<c;j++){
	    		   heights[i][j]=cin.nextInt();
	    	   }
	       }
	       int max=0;
	       for(int i=0;i<r;i++){
	    	   for(int j=0;j<c;j++){
	    		   int temp=maxHeight(heights,i,j,r,c);
	    		   max=temp>max?temp:max;
	    	   }
	       }
	       System.out.println(max);  
	}
	public static int maxHeight(int[][]a,int r,int c,int h,int w){
		if(result[r][c]!=0){
			return result[r][c];
		}
		int lefth = 0,righth=0,toph=0,bottomh=0;
		if(c>0&&a[r][c-1]<a[r][c]){
			lefth=maxHeight(a,r,c-1,h,w)+1;
		}
		if(c<(w-1)&&a[r][c+1]<a[r][c]){
			righth=maxHeight(a,r,c+1,h,w)+1;
		}
		if(r>0&&a[r-1][c]<a[r][c]){
			toph=maxHeight(a,r-1,c,h,w)+1;
		}
		if(r<(h-1)&&a[r+1][c]<a[r][c]){
			bottomh=maxHeight(a,r+1,c,h,w)+1;
		}
		int maxw=lefth>righth?lefth:righth;
		int maxh=toph>bottomh?toph:bottomh;
		if(maxh==0&&maxw==0){
			result[r][c]=1;
			return 1;
		}
		result[r][c]=maxw>maxh?maxw:maxh;
		return maxw>maxh?maxw:maxh;
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值