Problem
You are given an m x n
integer matrix grid
and an array queries
of size k
.
Find an array answer
of size k
such that for each integer queries[i]
you start in the top left cell of the matrix and repeat the following process:
- If
queries[i]
is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all4
directions: up, down, left, and right. - Otherwise, you do not get any points, and you end this process.
After the process, answer[i]
is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times.
Return the resulting array answer
.
Examples
Example 1:
$$ \begin{array}{|c|c|c|} \hline \colorbox{orange} 1 & \colorbox{orange} 2 & \colorbox{orange} 3 \\ \hline \colorbox{orange} 2 & 5 & 7 \\ \hline \colorbox{orange} 3 & 5 & 1 \\ \hline \end{array} \text{ }\text{ }\text{ }\text{ }\text{ } \begin{array}{|c|c|c|} \hline \colorbox{orange} 1 & \colorbox{orange} 2 & \colorbox{orange} 3 \\ \hline \colorbox{orange} 2 & \colorbox{orange} 5 & 7 \\ \hline \colorbox{orange} 3 & \colorbox{orange} 5 & \colorbox{orange} 1 \\ \hline \end{array} \text{ }\text{ }\text{ }\text{ }\text{ } \begin{array}{|c|c|c|} \hline \colorbox{orange} 1 & 2 & 3 \\ \hline 2 & 5 & 7 \\ \hline 3 & 5 & 1 \\ \hline \end{array} $$
|
|
Example 2:
$$ \begin{array}{|c|c|c|} \hline 5 & 2 & 1 \\ \hline 1 & 1 & 2 \\ \hline \end{array} $$
|
|
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
k == queries.length
1 <= k <= 104
1 <= grid[i][j], queries[i] <= 106
Solution
Method 1 - Using Binary search + Heap
The problem involves simulating a grid traversal for multiple queries. The task is to determine how many points can be collected starting from the top-left cell of the matrix, given the conditions that the current cell value should be strictly less than a query value for a point to be counted.
- Process the queries in sorted order, as this allows us to incrementally update which cells are accessible.
- Maintain a 2D grid representing visited cells. Use BFS or DFS to explore all cells satisfying the condition for the current query.
- For each query, return the number of reachable points in the matrix.
- Sort queries in ascending order and process them to reduce repeated traversal.
- Use BFS combined with a priority queue to rapidly traverse and update the grid.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k * (m * n))
in the worst-case scenario, wherek
is the number of queries,m
is the number of rows, andn
is the number of columns. - 🧺 Space complexity:
O(m * n)
to track visited cells and store intermediate grids.