题目地址:点击打开链接
思路:简单的记忆化搜索,我刚开始细节没注意错了一次,后来却因为判断语句里写错了一个变量wrong了无数发,汗
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
typedef long long ll;
using namespace std;
int a[110][110];
int dp[110][110];
int r,c;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int dfs(int x,int y)
{
int i;
if(dp[x][y] != 0)
{
return dp[x][y];
}
for(i=0; i<4; i++)
{
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if(newx >= 0 && newx < r && newy >= 0 && newy < c)//就是这把newx写成newy
{
if(a[newx][newy] < a[x][y])
{
dp[x][y] = max(dp[x][y],dfs(newx,newy));
}
}
}
dp[x][y] += 1;
return dp[x][y];
}
int main()
{
int i,j;
while(~scanf("%d%d",&r,&c))
{
memset(dp,0,sizeof(dp));
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d",&a[i][j]);
}
}
int min1 = 0;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
int lol = dfs(i,j);
if(lol > min1)
{
min1 = lol;
}
}
}
printf("%d\n",min1);
}
return 0;
}
错误代码1:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
typedef long long ll;
using namespace std;
int a[110][110];
int dp[110][110];
int r,c;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int dfs(int x,int y)
{
int i;
if(dp[x][y] != 0)
{
return dp[x][y];
}
for(i=0; i<4; i++)
{
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if(newx >= 0 && newx < r && newy >= 0 && newy < c)
{
if(a[newx][newy] < a[x][y])
{
dp[x][y] = max(dp[x][y],dfs(newx,newy));
}
}
}
return dp[x][y] + 1;//这里错是因为我没把dp[x][y]的值变过来,打算在主函数里变过来,可有时候不会变过来,因为有函数调用的关系
}
int main()
{
int i,j;
while(~scanf("%d%d",&r,&c))
{
memset(dp,0,sizeof(dp));
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d",&a[i][j]);
}
}
int min1 = 0;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
dp[i][j] = dfs(i,j);
if(dp[i][j] > min1)
{
min1 = dp[i][j];
}
}
}
printf("%d\n",min1);
}
return 0;
}
错误代码2:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
typedef long long ll;
using namespace std;
int a[110][110];
int dp[110][110];
int r,c;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int dfs(int x,int y)
{
int i;
if(dp[x][y] != 0)
{
return dp[x][y];
}
for(i=0; i<4; i++)
{
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if(newx >= 0 && newx < r && newy >= 0 && newy < c)
{
if(a[newx][newy] < a[x][y])
{
dp[x][y] = max(dp[x][y],dfs(newx,newy));
}
}
}
return dp[x][y] + 1;
}
int main()
{
int i,j;
while(~scanf("%d%d",&r,&c))
{
memset(dp,0,sizeof(dp));
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
scanf("%d",&a[i][j]);
}
}
int min1 = 0;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
int lol = dfs(i,j);
if(lol > min1)
{
min1 = lol;
}
}
}
printf("%d\n",min1);
}
return 0;
}
在上面错误代码上简单改一下就一下能测出错误之处