liuzhuoran141516 @ 2024-10-14 13:36:59
#include <bits/stdc++.h>
using namespace std;
int n, m, snow[105][105], out;
int slid(int x, int y, int l) {
int ans = l;
if (snow[x - 1][y] < snow[x][y] and x > 1) {
ans = max(ans, slid(x - 1, y, l + 1));
}
if (snow[x + 1][y] < snow[x][y] and x < n) {
ans = max(ans, slid(x + 1, y, l + 1));
}
if (snow[x][y - 1] < snow[x][y] and y > 1) {
ans = max(ans, slid(x, y - 1, l + 1));
}
if (snow[x][y + 1] < snow[x][y] and y < m) {
ans = max(ans, slid(x, y + 1, l + 1));
}
return ans;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j ++) {
cin >> snow[i][j];
}
}
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j ++) {
out = max(out, slid(i, j, 1));
}
}
cout << out;
return 0;
}
by KevinHu0402 @ 2024-10-14 13:53:00
稍微格式化了一下你的代码并 AC:
#include <bits/stdc++.h>
using namespace std;
int n, m;
int snow[105][105], dp[105][105];
int slid(int x, int y) {
if (dp[x][y] != -1) return dp[x][y];
int ans = 1;
if (x > 1 && snow[x - 1][y] < snow[x][y]) {
ans = max(ans, 1 + slid(x - 1, y));
}
if (x < n && snow[x + 1][y] < snow[x][y]) {
ans = max(ans, 1 + slid(x + 1, y));
}
if (y > 1 && snow[x][y - 1] < snow[x][y]) {
ans = max(ans, 1 + slid(x, y - 1));
}
if (y < m && snow[x][y + 1] < snow[x][y]) {
ans = max(ans, 1 + slid(x, y + 1));
}
dp[x][y] = ans;
return ans;
}
int main() {
cin >> n >> m;
memset(dp, -1, sizeof(dp));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> snow[i][j];
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ans = max(ans, slid(i, j));
}
}
cout << ans;
return 0;
}
by KevinHu0402 @ 2024-10-14 13:56:33
注意你的边界和返回函数,我修改了一下就 A 了。
by liuzhuoran141516 @ 2024-10-14 14:12:53
谢谢大佬,已关orz