Maximum Strictly Increasing Cells in a Matrix — LeetCode 2713 Python Solution
- Problem
- #2713
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell. From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell.
Example
- Input
- mat = [[3,1],[3,4]]
- Output
- 2
- Explanation
- The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2.
Python solution
class Solution:
def maxIncreasingCells(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
g = defaultdict(list)
for i in range(m):
for j in range(n):
g[mat[i][j]].append((i, j))
rowMax = [0] * m
colMax = [0] * n
ans = 0
for _, pos in sorted(g.items()):
mx = []
for i, j in pos:
mx.append(1 + max(rowMax[i], colMax[j]))
ans = max(ans, mx[-1])
for k, (i, j) in enumerate(pos):
rowMax[i] = max(rowMax[i], mx[k])
colMax[j] = max(colMax[j], mx[k])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n \times \log(m \times n)) |
| Space | O(m \times n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix?
- LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix?
- The Python solution on this page runs in O(m \times n \times \log(m \times n)).
- What is the space complexity of LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix cover?
- LeetCode 2713. Maximum Strictly Increasing Cells in a Matrix is tagged Memoization, Array, Hash Table, Binary Search, Dynamic Programming, Matrix, Ordered Set and Sorting on LeetCode.