Problem 695
Longest Increasing Path in a Matrix
Hard · 30 pts · Matrix, Depth-First Search, Dynamic Programming, Memoization
Problem
In an R × C matrix of integers, a path moves between cells that share a side (up, down, left or right) and must be strictly increasing along the way. Find the number of cells on the longest increasing path. No diagonal moves and no wrapping around the edges are allowed. Because the path is strictly increasing it can never loop, so a depth-first search with memoisation, storing the longest path that starts at each cell, solves it in O(R × C).
Input
The first line contains R and C. Each of the next R lines contains C integers.
Output
Print the length of the longest increasing path.
Constraints
1 <= R, C <= 200; 0 <= value <= 2^31 - 1
Example input
3 3 9 9 4 6 6 8 2 1 1
Example output
4
Explanation
In the matrix 9 9 4 / 6 6 8 / 2 1 1, the path 1 → 2 → 6 → 9 is strictly increasing and uses 4 cells. No longer increasing path exists, so the answer is 4.