……;
给出可以走的位置,问最多能爬多少层,使用dp,这道题有点不同的是还可以往下走,而常见的大都是递推,需要多加一个条件,谢谢Staginner大牛的指点!
dfs可能会超时(深度太大)?
为什么使用C++提交而不是C?在COJ上遭遇过使用C比C++耗时超出3s的经历(时限是5s)。
# include <stdio.h> # include <string.h> # define N 105 char map[N][N]; int n, m, f[N][N]; int dp(int i, int j); int main() { int i, j, h; while (~scanf("%d%d", &n, &m)) { for (i = n; i >= 1; --i) for (j = 1; j <= m; ++j) scanf("%d", &map[i][j]); h = 0; memset(f, -1, sizeof(f)); for (j = 1; j <= m; ++j) if (map[1][j] && h<dp(1,j)) h = f[1][j]; printf("%d\n", h); } return 0; } int dp(int i, int j) { if (f[i][j] >= 0) return f[i][j]; if (map[i][j]) f[i][j] = 1; else return f[i][j] = 0; if (i+1<=n && map[i+1][j] && f[i][j]<dp(i+1,j)+1) f[i][j] = f[i+1][j]+1; if (j+1<=m && map[i][j+1] && f[i][j]<dp(i,j+1)) f[i][j] = f[i][j+1]; if (j-1>=1 && map[i][j-1] && f[i][j]<dp(i,j-1)) f[i][j] = f[i][j-1]; if (i-1>=1 && map[i-1][j] && f[i][j]<dp(i-1,j)-1) f[i][j] = f[i-1][j]-1; return f[i][j]; }