Skip to main content
Back to problems
#2328
Hard Algorithms

Number of increasing paths in a grid

Array Dynamic Programming Depth-First Search Breadth-First Search Graph Theory Topological Sort Memoization Matrix
57.4% acceptance
Feb 25, 2026
2107
45
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 10^9 + 7.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn count_paths(grid: Vec<Vec<i32>>) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let m = grid.len();
    let n = grid[0].len();
    let mut dp = vec![vec![0i64; n]; m];

    let mut cells: Vec<(i32, usize, usize)> = Vec::with_capacity(m * n);
    for i in 0..m {
      for j in 0..n {
        cells.push((grid[i][j], i, j));
      }
    }
    cells.sort_unstable();

    let dirs: [(i32, i32); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)];
    let mut ans: i64 = 0;

    for (val, i, j) in cells {
      dp[i][j] = 1;
      for (di, dj) in dirs {
        let ni = i as i32 + di;
        let nj = j as i32 + dj;
        if ni >= 0 && ni < m as i32 && nj >= 0 && nj < n as i32 {
          let (ni, nj) = (ni as usize, nj as usize);
          if grid[ni][nj] < val {
            dp[i][j] = (dp[i][j] + dp[ni][nj]) % MOD;
          }
        }
      }
      ans = (ans + dp[i][j]) % MOD;
    }
    ans as i32
  }
}