原題鏈接 http://poj.org/problem?id=1088
Description
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
一個人可以從某個點滑向上下左右相鄰四個點之一,當且僅當高度減小。在上面的例子中,一條可滑行的滑坡爲24-17-16-1。當然25-24-23-...-3-2-1更長。事實上,這是最長的一條。
Input
Output
Sample Input
5 5 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
Sample Output
25
Source Code
/*
用DP[i][j]記錄從點map[i][j]出發的最長路徑(不算本身,只算延伸;也就是初始值爲0)
狀態轉移方程DP[i][j]=max{ DP[i+1][j], DP[i-1][j], DP[i][j+1], DP[i][j-1] } + 1
也就是說,DP[i][j]的值等於從map[i][j]的上下左右四個方向出發所滑的最長值+1;
而這道題並不是簡單的動歸,計算DP[i][j]的過程需要類似DFS的遞歸方法.這就是記憶化搜索.
*/
#include <iostream>
using namespace std;
#define Max 101
int map[Max][Max];
int result[Max][Max];
int dir[4][2] = {-1,0, 1,0, 0,1, 0,-1};
int row, column;
//判斷是否越過邊界
bool isInside(int x, int y) {
if (x < 0 || x >= row || y < 0 || y >= column){
return false;
}
return true;
}
//dfs過程:
//對於每一個點,首先判斷其最長路徑是否已經計算出來,如果已經計算出來就直接返回結果
//如果未計算出來,就判斷其上下左右四個方向是否有可以移動的點,如果有,就遞歸計算目的地點的最長路徑。
//最後取上下左右個方向的最大最長路徑,+1後即爲當前點的最長路徑
int DP(int x, int y) {
int i, newX, newY;
if (result[x][y] > 0) {
return result[x][y];
}
for (i = 0; i < 4; i++) {
newX = x + dir[i][0];
newY = y + dir[i][1];
if (isInside(newX, newY) && map[newX][newY] < map[x][y]) {
int temp = DP(newX, newY) + 1;
if (result[x][y] < temp) {
result[x][y] = temp;
}
}
}
return result[x][y];
}
int main() {
int i, j, maxstep;
while(scanf("%d %d", &row, &column) != EOF) {
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
scanf("%d", &map[i][j]);
}
}
maxstep = 0;
memset(result, 0, sizeof(result));
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
int temp = DP(i, j);
if (maxstep < temp) {
maxstep = temp;
}
}
}
printf("%d\n", maxstep + 1);
}
}