Maximum Number of Moves in a Grid — LeetCode 2684 Python Solution
- Problem
- #2684
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed m x n matrix grid consisting of positive integers. You can start at any cell in the first column of the matrix, and traverse the grid in the following way: From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell.
Example
- Input
- grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]
- Output
- 3
- Explanation
- We can start at the cell (0, 0) and make the following moves:
Python solution
class Solution:
def maxMoves(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
q = set(range(m))
for j in range(n - 1):
t = set()
for i in q:
for k in range(i - 1, i + 2):
if 0 <= k < m and grid[i][j] < grid[k][j + 1]:
t.add(k)
if not t:
return j
q = t
return n - 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2684. Maximum Number of Moves in a Grid 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 2684. Maximum Number of Moves in a Grid?
- LeetCode 2684. Maximum Number of Moves in a Grid is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2684. Maximum Number of Moves in a Grid?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 2684. Maximum Number of Moves in a Grid?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 2684. Maximum Number of Moves in a Grid cover?
- LeetCode 2684. Maximum Number of Moves in a Grid is tagged Array, Dynamic Programming and Matrix on LeetCode.