I have been presented with a new homework assignment that has been somewhat frustrating to say the least. Basically, I have a create a 2D array of integers as follows:
I learnt dynamic programming recently, and I have found a better algorithm for the question.
The algorithm is simple: find the longest length for every point, and record the result in a 2D array so that we do not need to calculate the longest length for some points again.
int original[m][n] = {...};
int longest[m][n] = {0};
int find() {
int max = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int current = findfor(i, j);
if (current > max) { max = current; }
}
}
return max;
}
int findfor(int i, int j) {
if (longest[i][j] == 0) {
int max = 0;
for (int k = -1; k <= 1; k++) {
for (int l = -1; l <= 1; l++) {
if (!(k == 0 && l == 0) &&
i + k >= 0 && i + k < m &&
j + l >= 0 && j + l < n &&
original[i + k][j + l] > original[i][j]
)
int current = findfor(i + k, j + l);
if (current > max) { max = current; }
}
}
}
longest[i][j] = max + 1;
}
return longest[i][j];
}
1) start with a point (and this step has to be taken for all necessary points)
2) if no surrounding point is greater, then this path ends; else pick a greater surrounding point to continue the path, and go to 2).
2.1) if the (ended) path is longer than recorded longest path, substitute itself as the longest.
(less computation but more coding)
For the longest path, the start point of which will be a local minimum point, and the end point of which will be a local maximum point.
Local minimum, less than (or equal to) all (at most) 8 surrounding points.
Local maximum, greater than (or equal to) all (at most) 8 surrounding points.
If the path does not start with a local minimum, then the start point must be greater than at least a surrounding point, and thus the path can be extended. Reject! Thus, the path must start with a local minimum. Similar for the reason to end with a local maximum.
for all local minimum
do a recursive_search
recursive_search (point)
if point is local maximum
end, and compare (and substitute if necessary) longest
else
for all greater surrounding points
do a recursive_search