Number of Increasing Paths in a Grid - Problem
Imagine you're exploring a mountainous terrain represented by a grid where each cell contains an elevation value. You can move to any of the 4 adjacent cells (up, down, left, right), but there's a catch - you can only move to cells with strictly higher elevation!
Given an m x n integer matrix grid, your task is to find the total number of strictly increasing paths possible in this terrain. You can start from any cell and end at any cell, as long as each step takes you to a higher elevation.
Key Points:
- Two paths are different if they visit different sequences of cells
- A single cell counts as a valid path of length 1
- Return the answer modulo
109 + 7since it can be very large
Example: In a 2x2 grid [[1,1],[3,4]], you have paths like: [1]→[3]→[4], [1]→[3], [3]→[4], and all single cells, totaling 8 different increasing paths.
Input & Output
example_1.py — Basic Grid
$
Input:
grid = [[1,1],[3,4]]
›
Output:
8
💡 Note:
The 8 increasing paths are: [1], [1], [3], [4], [1,3], [1,4], [1,3,4], [3,4]. Note that paths [1,3,4] and [1,4] start from different cells with value 1.
example_2.py — Single Row
$
Input:
grid = [[1]]
›
Output:
1
💡 Note:
There's only one cell, so there's exactly one path consisting of just that single cell [1].
example_3.py — Larger Grid
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
109
💡 Note:
This 3x3 grid has many possible increasing paths. Each cell can potentially reach multiple higher-valued cells, creating numerous path combinations.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 1000
- 1 ≤ grid[i][j] ≤ 105
- All values in the grid are unique
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Grid
Each cell represents an elevation point. We need to find all strictly increasing paths.
2
DFS with Memoization
From each cell, explore all 4 directions and count paths to higher elevation cells.
3
Cache Results
Store the number of paths from each cell to avoid recalculation.
4
Sum All Paths
Add up all possible increasing paths from every starting cell.
Key Takeaway
🎯 Key Insight: Use memoization to transform an exponential brute force solution into an efficient O(m×n) algorithm by caching path counts for each cell.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code