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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code