Number of Increasing Paths in a Grid

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 109 + 7.

Two paths are considered different if they do not have exactly the same sequence of visited cells.

 

Example 1:

Input: grid = [[1,1],[3,4]]
Output: 8
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [1], [3], [4].
- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].
- Paths with length 3: [1 -> 3 -> 4].
The total number of paths is 4 + 3 + 1 = 8.

Example 2:

Input: grid = [[1],[2]]
Output: 3
Explanation: The strictly increasing paths are:
- Paths with length 1: [1], [2].
- Paths with length 2: [1 -> 2].
The total number of paths is 2 + 1 = 3.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 105
  • 1 <= grid[i][j] <= 105
SOLUTION:
class Solution:
    def getNeighbours(self, i, j, m, n):
        for x, y in [(i - 1, j), (i, j + 1), (i + 1, j), (i, j - 1)]:
            if 0 <= x < m and 0 <= y < n:
                yield (x, y)
    
    def numInc(self, matrix, i, j, m, n):
        if (i, j) in self.cache:
            return self.cache[(i, j)]
        res = 1
        for x, y in self.getNeighbours(i, j, m, n):
            if matrix[x][y] > matrix[i][j]:
                curr = self.numInc(matrix, x, y, m, n)
                res += curr
        self.cache[(i, j)] = res
        return res
    
    def countPaths(self, matrix: List[List[int]]) -> int:
        m = len(matrix)
        n = len(matrix[0])
        self.cache = {}
        res = 0
        for i in range(m):
            for j in range(n):
                res += self.numInc(matrix, i, j, m, n)
        return res % (10 ** 9 + 7)

Comments

Popular posts from this blog

Encrypt and Decrypt Strings

Degree of an Array

Minimum Sum of Four Digit Number After Splitting Digits