#include <iostream> #include <algorithm> using namespace std; #define N 100 int m,n; int high[N][N]={0}; int len[N][N] = {0};//将每个数的最长下降长度记录下来,在递归的时候可以避免每次遍历所有点 int nextGo[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向 int dp(int i,int j){ if (len[i][j] != 0) { return len[i][j]; } int x,y,mx=0; for(int k=0;k<4;k++){ x = i + nextGo[k][0]; y = j + nextGo[k][1]; if (x < 0 || x > m - 1 || y < 0 || y > n - 1) {//将出界的情况跳过 continue; } if (high[i][j] > high[x][y]) { mx = max(mx, dp(x, y));//选择自己最大序列下降 } } len[i][j] = mx + 1;//自己本身也有长度1 return len[i][j]; } int main() { cin>>m>>n; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cin >> high[i][j]; } } int result = 0;//所有点里选择最长的 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { result = max(result, dp(i, j)); } } cout<<result<<endl; return 0; }
对出界情况的处理是从别人代码里学到的