2328. Number of Increasing Paths in a Grid

Hard

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.

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 <= 10^5

  • 1 <= grid[i][j] <= 10^5

解題

參考解法影片


const mod = 1000000007

func countPaths(grid [][]int) int {
	dp := make([][]int, len(grid))
	for i := range grid {
		dp[i] = make([]int, len(grid[i]))
	}

	result := 0
	for i := 0; i < len(grid); i++ {
		for j := 0; j < len(grid[0]); j++ {
			result = (result + search(grid, dp, 10000001, i, j)) % mod
		}
	}
	return result
}

func search(grid, dp [][]int, previousValue, x, y int) int {
	if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) || previousValue <= grid[x][y] {
		return 0
	}

	if dp[x][y] > 0 {
		return dp[x][y]
	}

	dp[x][y] = 1

	dp[x][y] += search(grid, dp, grid[x][y], x-1, y) % mod
	dp[x][y] += search(grid, dp, grid[x][y], x+1, y) % mod
	dp[x][y] += search(grid, dp, grid[x][y], x, y-1) % mod
	dp[x][y] += search(grid, dp, grid[x][y], x, y+1) % mod
	return dp[x][y]
}

之前的錯誤解法:

func countPaths(grid [][]int) int {
    mod := 1000000007
    dr := []int{1, 0, -1, 0}
    dc := []int{0, 1, 0, -1}

    dp := make([][]int, len(grid))
    for i:=0; i<len(dp); i++ {
        dp[i] = make([]int, len(grid[0]))
    }

    var dfs  func(int, int) int
    dfs = func(r int, c int) int {
        if dp[r][c] > 0 {
            return dp[r][c]
        }

        dp[r][c] = 1
        
        for i:=0; i<4; i++ {
            nr := r + dr[i]
            nc := r + dc[i]

            if nr >= 0 && nr < len(grid) && nc >= 0 && nc < len(grid[0]) && grid[nr][nc] > grid[r][c] {
                dp[r][c] = (dp[r][c]%mod + dfs(nr,nc)%mod)%mod
            } 
        }
        
        return dp[r][c]
    }

    res := 0

    for i:=0; i<len(grid); i++ {
        for j:=0; j<len(grid[0]); j++ {
            res = (res%mod + dfs(i, j)%mod)%mod
        }
    }

    return res
}

Last updated