Problem Description
Given a 1-indexed m x n integer matrix mat, you can begin at any cell. From a starting cell, you are allowed to move to any other cell in the same row or column, but only if the destination cell's value is strictly greater than the current cell's value. The goal is to determine the maximum number of cells you can visit by making a sequence of such moves.
Key Insights
- We can only move from a cell to another in the same row or column if the destination value is greater.
- The problem is a variant of longest increasing sequence but on a 2D grid with row/column moves.
- Instead of considering direct neighbours, we are allowed to jump arbitrarily within a row or column.
- Sorting cells by their value and using dynamic programming (DP) allows us to compute the best path lengths, while taking care of updates on each row and column.
- Grouping cells with the same value ensures that they do not affect each other’s DP calculation (a cell can only come from a strictly smaller value).
Space and Time Complexity
Time Complexity: O(mn × log(mn)) due to sorting all cells. Space Complexity: O(m*n + m + n) for storing DP states, row and column maximums and the sorted list of cells.
Solution
We solve the problem by:
- Creating a list of all cell positions along with their values.
- Sorting the cells by value.
- Using dynamic programming, for a cell at (i, j), the best path (dp[i][j]) is determined by 1 plus the maximum value among the currently stored maximums for that row and column.
- To handle cells with the same value (since moves must be strictly increasing) we process them in groups. For each group of cells with the same value, we calculate their DP values based solely on previous groups (cells with smaller values). After processing the group, we update the maximum path values for their corresponding row and column.
- The final answer is the maximum DP value encountered.
Key data structures include:
- A DP table (implicit in our calculation) stored per cell.
- Two arrays, one for each row and one for each column, holding the best (maximum) DP value for that row/column so far.
This approach ensures that each cell’s solution builds only on previously computed states, maintaining the strictly increasing property.