Description
It's no surprise that Michael loves skiing, because skiing is really exciting. But to gain speed, the slippery area has to slope down, and when you get to the bottom of the slope, you have to walk uphill again or wait for the lift to pick you up. Michael wants to know the longest landslide in an area. The area is given by a two-dimensional array. Each number of the array represents the height of the point. Below is an example
A person can slide from a point up, down, left and right to one of the four adjacent points if and only if the height decreases. In the example above, a slideable landslide is 24-17-16-1. Of course 25-24-23-...-3-2-1 is longer. In fact, this is the longest one.
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
A person can slide from a point up, down, left and right to one of the four adjacent points if and only if the height decreases. In the example above, a slideable landslide is 24-17-16-1. Of course 25-24-23-...-3-2-1 is longer. In fact, this is the longest one.
Input
The first line of input represents the row number R and column number C of the region (1 <= R, C <= 100). Below are R lines, each with C integers representing height h, 0<=h<=10000.
Output
Output the length of the longest region.
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
My favorite POJ Chinese questions
Analysis: You can use deep search dfs to find the longest path from each point and compare the size, but this will definitely time out, so we can also record the points found halfway during dfs, because at the beginning When defining the array, the array is all 0, so when traversing each point at the beginning, if the traversed point is not equal to 0, it means that the deep search of the previous point has passed through this point and has been recorded, and it will return directly. .
#include <cstring> #include<algorithm> #include <iostream> #include<cmath> #define INF -1; using namespace std; int dir[4][2] = { { -1,0 },{ 0,1 },{ 1,0 },{ 0,-1 } }; int dp[101][101], len[101][101]; int r, c; int dfs(int i, int j) { if (len[i][j] != 0) return len[i][j]; int maxn = 0, s; for (int t = 0; t < 4; t++) { int x = i + dir[t][0]; int y = j + dir[t][1]; if (x >= 0 && x < r&&y >= 0 && y < c&&dp[x][y] < dp[i][j]) { s = dfs(x, y); if (s > maxn) maxn = s; } } len[i][j] = maxn + 1; return maxn + 1; } int main() { int Min = INF; cin >> r >> c; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> dp[i][j]; } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { Min = max(Min, dfs(i, j));z } } cout << Min << endl; return 0; }