crzcqh @ 2023-07-11 14:51:30
#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[105][105],f[105][105],vist[105][105],ans;
void dfs(int x,int y,int s){
if(vist[x][y]) return ;
if(x<1||x>n||y<1||y>m) return;
if(a[x][y]<s) return ;
if(f[x][y]) return ;
vist[x][y]=1;
dfs(x+1,y,a[x][y]);
dfs(x-1,y,a[x][y]);
dfs(x,y+1,a[x][y]);
dfs(x,y-1,a[x][y]);//搜索四个方向
vist[x][y]=0;
f[x][y]=max(
max(f[x+1][y],f[x-1][y]),
max(f[x][y+1],f[x][y-1])
)+1;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){//每个店都做起始点遍历一遍。
dfs(i,j,a[i][j]);
ans=max(f[i][j],ans);
}
}
cout<<ans;
return 0;
}
by crzcqh @ 2023-07-11 14:51:59
4个点WA
by 0x282e202e2029 @ 2023-07-11 14:58:12
记忆化搜索。在搜索每个方向前先判断即可。
#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
int n, m, ans;
int a[105][105], rec[105][105];
int dfs(int x, int y)
{
if(rec[x][y])
{
return rec[x][y];
}
rec[x][y] = 1;
int nx, ny;
for(int i = 0; i < 4; i++)
{
nx = x + dx[i], ny = y + dy[i];
if(0 < nx && 0 < ny && nx <= n && ny <= m && a[x][y] > a[nx][ny])
{
dfs(nx, ny);
rec[x][y] = max(rec[x][y], rec[nx][ny] + 1);
}
}
return rec[x][y];
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> a[i][j];
}
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
ans = max(ans, dfs(i, j));
}
}
cout << ans;
return 0;
}
by 0x282e202e2029 @ 2023-07-11 15:00:16
@crzcqh
by crzcqh @ 2023-07-11 15:04:31
谢谢dalao!