Maximum Number of Moves in a Grid - Problem

Imagine you're a chess knight, but with special movement rules! You're given an m x n matrix filled with positive integers, and you can start at any cell in the first column.

Your goal is to traverse as far right as possible, but there's a catch: you can only move to cells with strictly larger values!

From any cell (row, col), you have three possible moves:

  • 🔼 Up-right: (row-1, col+1)
  • ➡️ Right: (row, col+1)
  • 🔽 Down-right: (row+1, col+1)

Each move must be to a cell with a strictly greater value than your current position. Return the maximum number of moves you can make before getting stuck!

Input & Output

example_1.py — Basic Grid
$ Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]
Output: 3
💡 Note: Starting from (0,0) with value 2: move to (1,1) with value 4, then to (1,2) with value 9, then to (2,3) with value 11. Total moves: 3.
example_2.py — Single Row
$ Input: grid = [[3,2,4],[2,1,9],[1,1,7]]
Output: 0
💡 Note: No matter which starting position we choose from the first column, we cannot make any valid moves because all adjacent cells in the next column have smaller or equal values.
example_3.py — Increasing Path
$ Input: grid = [[1,2,3,4],[2,3,4,5],[3,4,5,6]]
Output: 3
💡 Note: Starting from any cell in the first column, we can move right through all columns since each column has strictly increasing values. Maximum moves = 3.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 2 ≤ m, n ≤ 1000
  • 4 ≤ m * n ≤ 105
  • 1 ≤ grid[i][j] ≤ 106

Visualization

Tap to expand
Maximum Number of Moves in a Grid INPUT col0 col1 col2 col3 2 4 3 5 5 4 9 3 3 4 2 11 10 9 13 15 Movement Rules: From (r,c) can move to: (r-1, c+1) up-right (r, c+1) right (r+1, c+1) down-right Constraint: Next cell value must be LARGER ALGORITHM STEPS 1 Initialize DP Table dp[i][j] = max moves from (i,j) 2 Process Right to Left Start from col n-2 to col 0 3 Check 3 Directions Up-right, Right, Down-right 4 Find Maximum Max from any cell in col 0 DP Table (max moves): 3 2 1 0 0 0 0 0 3 2 0 0 0 0 1 0 FINAL RESULT Optimal Path Found: 2 4 3 5 5 4 9 3 3 4 2 11 10 9 13 15 Path: 2 --> 4 --> 9 --> 11 (0,0) --> (0,1) --> (1,2) --> (2,3) OUTPUT 3 3 moves made! Key Insight: Use Dynamic Programming from right to left columns. For each cell, compute max moves by checking all valid transitions to cells with strictly larger values. The answer is the maximum dp value in column 0. Time: O(m*n), Space: O(m*n) - can be optimized to O(m) using column-by-column processing. TutorialsPoint - Maximum Number of Moves in a Grid | Optimal DP Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen