Problem Description
Given an m x n integer matrix grid, you can move from a cell to any of its 4 adjacent neighbors (up, down, left, right). A strictly increasing path is a sequence of cells where each subsequent cell has a value greater than the previous one. Count the total number of strictly increasing paths in the grid (a path can start and end at any cell), and return the result modulo 10^9 + 7.
Key Insights
- Every single cell is a valid increasing path of length one.
- The movement is allowed in all four directions; the condition is that the next value must be strictly greater.
- Use Depth-First Search (DFS) with memoization (or dynamic programming) to count paths starting from each cell.
- Since a cell’s optimal result may overlap with neighbor computations, caching the results avoids redundant calculations.
- The grid values themselves impose a natural order, allowing a topological-style processing if needed.
Space and Time Complexity
Time Complexity: O(m * n) since each cell is processed once and each DFS considers 4 directions. Space Complexity: O(m * n) for the memoization table and recursion stack (in worst-case scenarios).
Solution
We use DFS with memoization to count the number of increasing paths starting from each cell. For each cell, if it hasn't been computed before (i.e., memoized), we count one path (the cell itself) plus the paths obtainable by moving in any valid (increasing) direction. The computed result for each cell is stored in a dp table to prevent recalculating overlapping subproblems. Finally, sum the number of paths from all cells, applying modulo 10^9 + 7 at each step.