MediumNo. 2684

Maximum Number of Moves in a Grid — LeetCode 2684 Python Solution

Topics
Array, Dynamic Programming, Matrix
Reading time
3 min

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

PythonSolution
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 - 1

Complexity

Time
O(m × n)
Space · auxiliary
O(m)

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

Related problems
No.ProblemDifficulty
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard
0174Dungeon GameHard
0221Maximal SquareMedium
0329Longest Increasing Path in a MatrixHard

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 × 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.