大年初一,开始练习动态规划。
题目:
个人感觉主要思路就是还递归,只不过递归的同时记录结果节省时间,代码还可以进一步优化写成递推公式的形式
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int h[105][105];
int db[105][105];
int R,C;
int res;
int max4(int a,int b,int c,int d){
return max(max(a,b),max(c,d));
}
int sc(int y,int x){
int d1=0,d2=0,d3=0,d4=0;
if(h[y-1][x]<h[y][x]&&y>=1){
if(db[y-1][x]){
d1=db[y-1][x];
}else d1=sc(y-1,x);
};
if(h[y+1][x]<h[y][x]&&y+1<R){
if(db[y+1][x]){
d2=db[y+1][x];
}else d2=sc(y+1,x);
};
if(h[y][x-1]<h[y][x]&&x>=1){
if(db[y][x-1]){
d3=db[y][x-1];
}else d3=sc(y,x-1);
}
if(h[y][x+1]<h[y][x]&&x+1<C){
if(db[y][x+1]){
d4=db[y][x+1];
}else d4=sc(y,x+1);
};
db[y][x]+=max4(d1,d2,d3,d4)+1;
if(db[y][x]>res)res=db[y][x];
return db[y][x];
}
int main(){
int N;
scanf("%d",&N);
while(N--){
res=0;
scanf("%d%d",&R,&C);
for(int i=0;i<R;i++)
for(int j=0;j<C;j++){
scanf("%d",&h[i][j]);
db[i][j]=0;
}
for(int i=0;i<R;i++)
for(int j=0;j<C;j++){
if(!db[i][j]){
sc(i,j);
}
}
printf("%d\n",res);
}
return 0;
}