题目:
Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你。Michael想知道载一个区域中最长的滑坡。区域由一个二维数组给出。数组的每个数字代表点的高度。下面是一个例子
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
输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
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
思路:
用记忆化的搜索,构造以每个点为起点的最长下降路径,结合DP的状态方程:
DP[i][j] =1+ max(DP[i-1][j], DP[i+1][j], DP[i][j-1], DP[i][j+1]),( if map[i][j] > map[x][y] && (x,y) in the map )。
MyCode:
#pragma once #include <iostream> const int row = 5; const int col = 5; int getMaxRoute(int arr[row][col], int resArr[row][col], int rowIdx, int colIdx); int main() { int arr[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 }; int resArr[row][col] ={ 0 }; //保存找出的结果,记忆,辅助。 int countR = getMaxRoute(arr, resArr,0,2); std::cout <<"res(0,2)= "<< countR <<std::endl ; countR = getMaxRoute(arr, resArr, 2, 2); std::cout << "res(2,2)= " << countR << std::endl; //找出一个最长的路径 int totalMaxRouteLen = 0; for (int rowIdx = 0; rowIdx < row; rowIdx++) { for (int coluIdx = 0; coluIdx < col; coluIdx++) { int countR = getMaxRoute(arr, resArr, rowIdx, coluIdx); if (countR > totalMaxRouteLen) totalMaxRouteLen = countR; } } std::cout << "totalMaxRouteLen = " << totalMaxRouteLen << std::endl; return 0; } //给定一个起点,找出以此为起始点的最长下坡的长度。递归-动态-充分利用已经找到的信息 int getMaxRoute(int arr[row][col], int resArr[row][col], int rowIdx, int colIdx) { if (rowIdx >= row) return 0; if (colIdx >= col) return 0; if (resArr[rowIdx][colIdx] > 0)//该起点已经搞定了 return resArr[rowIdx][colIdx]; int maxRouteLen = 1; //如果该点的上下左右四个邻居都比它大,则以其为起点的路径长度记为1. if (rowIdx - 1 >= 0)//up side { if (arr[rowIdx - 1][colIdx] < arr[rowIdx][colIdx]) { int subRouteLen = getMaxRoute(arr, resArr, rowIdx - 1, colIdx); if (subRouteLen + 1 > maxRouteLen) maxRouteLen = subRouteLen + 1; } } if (rowIdx + 1 < row)//down side { if (arr[rowIdx + 1][colIdx] < arr[rowIdx][colIdx]) { int subRouteLen = getMaxRoute(arr, resArr, rowIdx + 1, colIdx); if (subRouteLen + 1 > maxRouteLen) maxRouteLen = subRouteLen + 1; } } if (colIdx - 1 >= 0)//left side { if (arr[rowIdx][colIdx - 1] < arr[rowIdx][colIdx]) { int subRouteLen = getMaxRoute(arr, resArr, rowIdx, colIdx - 1); if (subRouteLen + 1 > maxRouteLen) maxRouteLen = subRouteLen + 1; } } if (colIdx + 1 < col)//right side { if (arr[rowIdx][colIdx + 1] < arr[rowIdx][colIdx]) { int subRouteLen = getMaxRoute(arr, resArr, rowIdx, colIdx + 1); if (subRouteLen + 1 > maxRouteLen) maxRouteLen = subRouteLen + 1; } } resArr[rowIdx][colIdx] = maxRouteLen; return maxRouteLen; }--
https://www.iteye.com/blog/cavenkaka-1318600
https://blog.csdn.net/qq_39435120/article/details/79731250