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 + 7 since 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
Number of Increasing Paths in a Grid INPUT Mountain Grid (Elevation) 1 1 3 4 [0,0] [0,1] [0] [1] Movement: 4 directions (up, down, left, right) Only to HIGHER elevation! grid = [[1,1], [3,4]] ALGORITHM (DFS) 1 Initialize Create memo table (m x n) 2 DFS from each cell Explore all starting points 3 Count paths Move only to higher values 4 Memoize results Cache to avoid recompute Paths from each cell: 2 cell[0,0] 2 cell[0,1] 2 cell[1,0] 1 cell[1,1] Sum = 2+2+2+1 = 7 + 1 = 8 FINAL RESULT All 8 Increasing Paths: [1] from (0,0) [1] from (0,1) [3] from (1,0) [4] from (1,1) [1] --> [3] from (0,0) [1] --> [3] from (0,1) [3] --> [4] from (1,0) [1] --> [3] --> [4] 1 1 3 4 Output: 8 Key Insight: DFS with memoization counts all strictly increasing paths efficiently. Each cell stores the total number of paths starting from it. Time: O(m*n), Space: O(m*n). Result modulo 10^9+7 handles large numbers. TutorialsPoint - Number of Increasing Paths in a Grid | DFS Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
67.3K Views
High Frequency
~25 min Avg. Time
1.8K 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