使用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; } }