洛谷P1434 [SHOI2002]滑雪(dfs+记忆化搜索)
关于记忆化搜索:https://blog.csdn.net/hjf1201/article/details/78680814
题目链接:https://www.luogu.org/problem/P1434
思路:将已经搜过的点的结果存起来,当下一次需要搜索这个点时,直接用存储的结果,返回。注意求的是最长路径
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <queue> #include <vector> #include <cstring> #include <map> #define mem(a) memset(a,0,sizeof(a)) using namespace std; typedef long long lll; const int maxn = 200005; const lll INF = 0x3f3f3f3f3f; int dir[8][2]= {2,1,1,2,-2,1,-1,2,2,-1,1,-2,-2,-1,-1,-2}; int dir2[4][2]= {0,1,0,-1,1,0,-1,0}; bool flag; int a[105][105],vis[105][105],ans,r,c; int dfs(int x, int y){ // cout << x <<" "<<y <<" "<< cnt << endl; // vis[x][y] = 1; if(vis[x][y] != 0) return vis[x][y]; int t ,tt = 1,i; for(i = 0; i < 4; i++) { int fx = x + dir2[i][0],fy = y + dir2[i][1]; if(fx > 0 && fx < r+1 && fy > 0 && fy < c+1 && a[fx][fy] < a[x][y]) { t = dfs(fx,fy) + 1; tt = max(t,tt); } } vis[x][y] = max(tt,vis[x][y]); return vis[x][y]; } int main() { cin >>r >> c; for(int i = 1; i <= r; i++) { for(int j = 1; j<= c; j++) cin >> a[i][j]; } for(int i = 1; i <= r; i++) { for(int j = 1; j <= c; j++) { //cout << "==============" << endl; //cout << "i = "<< i<<" j = "<< j<< endl; vis[i][j] = dfs(i,j);; ans = max(ans,vis[i][j]); // cout << "==============" << endl; } } cout << ans << endl; return 0; }