leetcode - 2328. Number of Increasing Paths in a Grid

Description

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:
leetcode - 2328. Number of Increasing Paths in a Grid_第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 <= 10^5
1 <= grid[i][j] <= 10^5

Solution

Use dp[i][j] to denote the result that we start with grid[i][j], then we will start with the maximum. Firstly use a heap to sort all the values from maximum to minimum, then we add the current position to the neighbor position. The final result would be the sum of dp array.

Time complexity: o ( m ∗ n ) o(m*n) o(mn)
Space complexity: o ( m ∗ n ) o(m*n) o(mn)

Code

class Solution:
    import heapq
    def countPaths(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        dp = [[1] * n for _ in range(m)]
        max_heap = []
        for i in range(m):
            for j in range(n):
                heapq.heappush(max_heap, (-grid[i][j], i, j))
        # start with the maximum
        while max_heap:
            value, i, j = heapq.heappop(max_heap)
            for x, y in zip((i - 1, i + 1, i, i), (j, j, j - 1, j + 1)):
                if 0 <= x < m and 0 <= y < n:
                    if grid[x][y] < grid[i][j]:
                        dp[x][y] += dp[i][j]
        return sum(sum(row) for row in dp) % 1000000007

你可能感兴趣的:(OJ题目记录,leetcode,动态规划,算法)