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 (1,0) with value 5: move to (0,1) with value 4, then to (0,2) with value 9, then to (1,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
Mountain Climbing Adventure24911๐Ÿ”๏ธ Path: 2 โ†’ 4 โ†’ 9 โ†’ 11๐Ÿ“ Total moves: 3๐ŸŽฏ Strategy: Always climb to higher elevations
Understanding the Visualization
1
Choose starting point
Start at any base camp in the first valley (first column)
2
Plan the route
From each position, check three possible paths: up-right, right, down-right
3
Climb higher
Only move to positions with higher elevation (greater values)
4
Find longest path
Use dynamic programming to efficiently find the path with maximum steps
Key Takeaway
๐ŸŽฏ Key Insight: By using dynamic programming and processing from right to left, we can efficiently calculate the maximum moves from any starting position without redundant calculations.
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