记忆化搜索代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int Map[105][105], Step[105][105];
int nx[] = {0, 1, 0, -1};
int ny[] = {1, 0, -1, 0};
int R, C, ans;
int dfs(int r, int c)
{
if(Step[r][c] != -1)
return Step[r][c];
Step[r][c] = 1;
for(int i = 0; i < 4; i++)
{
int tx = r+nx[i];
int ty = c+ny[i];
if(tx >= R || tx < 0 || ty >= C || ty < 0)
continue;
if(Map[tx][ty] >= Map[r][c])
continue;
Step[r][c] = max(Step[r][c], dfs(tx, ty) + 1);
}
return Step[r][c];
}
int main()
{
while(scanf("%d%d", &R, &C) != EOF)
{
memset(Step, -1, sizeof(Step));
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
scanf("%d", &Map[i][j]);
ans = -0x3f3f3f3f;
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
ans = max(ans, dfs(i, j));
cout << ans << endl;
}
return 0;
}
dp思路:对高度从小到大进行排序,在i点的时候,遍历0~i-1个点(升序排序,i前面的点的高度一定小于等于i),取相邻点间的大的路径长度
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
struct node
{
int r, c, h, dp;
}Map[10060];
bool cmp(node a, node b)
{
return a.h < b.h;
}
int main()
{
int R,C, cnt, ans;
while(scanf("%d%d", &R, &C) != EOF)
{
cnt = 0;
ans = 1;
for(int i = 0; i < R; i++)
for(int j = 0; j < C; j++)
{
scanf("%d", &Map[cnt].h);
Map[cnt].r = i;
Map[cnt].c = j;
Map[cnt++].dp = 1;
}
sort(Map, Map+cnt, cmp);
//cout << cnt << endl;
for(int i = 0; i < cnt; i++)
{
int row1 = Map[i].r;
int column1 = Map[i].c;
for(int j = 0; j < i;j++)
{
int row2 = Map[j].r;
int column2 = Map[j].c;
if(((row1 == row2 && abs(column1 - column2) == 1) || (column1 == column2 && abs(row1 - row2) == 1)) && Map[i].h > Map[j].h)
{
Map[i].dp = max(Map[i].dp, Map[j].dp + 1);
ans = max(ans, Map[i].dp);
}
}
}
cout << ans << endl;
}
return 0;
}