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. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.
Your task is to find the maximum number of cells that you can visit in the matrix by starting from some cell.
Return an integer denoting the maximum number of cells that can be visited.
Example 1:
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.
Example 2:
Input: mat = [[1,1],[1,1]] Output: 1 Explanation: Since the cells must be strictly increasing, we can only visit one cell in this example.
Example 3:
Input: mat = [[3,1,6],[-9,5,7]] Output: 4 Explanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 105
1 <= m * n <= 105
-105 <= mat[i][j] <= 105
Companies: Google
Related Topics:
Array, Binary Search, Dynamic Programming, Memoization, Sorting, Matrix
Similar Questions:
Let dp[i][j]
be the maximum steps we can go from a starting point.
dp[i][j] = max({max steps in row}, {max steps in column}) + 1
Since we always want to visit the cells in ascending order of values, we sort (i,j)
by value of A[i][j]
. We can do this using a map<int, vector<int>> m
where the keys are cell values and values are arrays of encoded (i,j)
positions in form of i * N + j
.
We log the maximum steps of row i
in ans[i]
and maximum steps of column j
in ans[M + j]
.
So, dp[i][j] = max(ans[i], ans[M + j]) + 1
.
// OJ: https://leetcode.com/problems/maximum-strictly-increasing-cells-in-a-matrix
// Author: github.com/lzl124631x
// Time: O(MNlogMN)
// Space: O(MN)
class Solution {
public:
int maxIncreasingCells(vector<vector<int>>& A) {
int M = A.size(), N = A[0].size();
map<int, vector<int>> m;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
m[A[i][j]].push_back(i * N + j);
}
}
vector<vector<int>> dp(M, vector<int>(N));
vector<int> ans(M + N);
for (auto &[val, pos] : m) {
for (int p : pos) {
int i = p / N, j = p % N;
dp[i][j] = max(ans[i], ans[M + j]) + 1;
}
for (int p : pos) {
int i = p / N, j = p % N;
ans[M + j] = max(ans[M + j], dp[i][j]);
ans[i] = max(ans[i], dp[i][j]);
}
}
return *max_element(begin(ans), end(ans));
}
};