Maximum Strictly Increasing Cells in a Matrix - Problem
Imagine you're a treasure hunter exploring a mysterious grid-based dungeon where each cell contains a magical number. You can start from any cell and move to other cells in the same row or column, but there's a catch: you can only move to cells with strictly greater values than your current position!
Given an m x n integer matrix, your goal is to find the maximum number of cells you can visit by choosing the optimal starting position and making the smartest moves possible.
Movement Rules:
- Start from any cell in the matrix
- Move only within the same row or column
- Destination cell value must be strictly greater than current cell
- Continue until no valid moves remain
Goal: Return the maximum number of cells that can be visited in a single journey.
Input & Output
example_1.py โ Basic Matrix
$
Input:
mat = [[3,1,6],[-9,5,7]]
โบ
Output:
4
๐ก Note:
The optimal path is: -9 โ 5 โ 7 โ 6. Start at (-9) in position (1,0), move to (5) in same row at (1,1), then move to (7) in same row at (1,2), finally move to (6) in same column at (0,2). This gives us a path of length 4.
example_2.py โ Single Row
$
Input:
mat = [[7,6,3]]
โบ
Output:
1
๐ก Note:
Since all movements must be to strictly greater values, and this row is in decreasing order, we can only visit one cell. No matter which cell we start from, there are no valid moves to cells with greater values.
example_3.py โ Perfect Increasing
$
Input:
mat = [[1,2],[3,4]]
โบ
Output:
3
๐ก Note:
Multiple optimal paths exist: 1โ2โ4 or 1โ3โ4, both having length 3. We can start at (1) and move to either (2) or (3), then continue to (4) for a total of 3 cells visited.
Constraints
- m == mat.length
- n == mat[i].length
- 1 โค m, n โค 105
- 1 โค m * n โค 105
- -105 โค mat[i][j] โค 105
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Terrain
Look at the matrix and identify all possible starting positions and their neighboring cells with greater values.
2
Plan the Route
Start from the lowest values and work your way up, building optimal paths incrementally.
3
Track Progress
Use dynamic programming to remember the best path length achievable from each position.
4
Find the Peak
The maximum value in your DP table represents the longest possible journey.
Key Takeaway
๐ฏ Key Insight: Process cells in ascending order of values - this ensures optimal substructure and eliminates the need for complex memoization!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code