cjql / algorithm

https://cjql.github.io/algorithm/
1 stars 1 forks source link

LeetCode https://leetcode.com/problems/matrix-block-sum/ dynamic programming #3

Open cjql opened 4 years ago

cjql commented 4 years ago

C++

Java

Python

class Solution:
    def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
        m,n = len(mat),len(mat[0])
        sum = [[0]*(n+1) for _ in range(m+1)]
        for i in range(m):
            for j in range(n):
                sum[i+1][j+1] = mat[i][j] - sum[i][j] + sum[i][j+1] + sum[i+1][j]
        result = [[0]*n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                r1, c1, r2, c2 = max(0, i - K), max(0, j - K), min(m, i + K + 1), min(n, j + K + 1)
                result[i][j] = sum[r1][c1]+sum[r2][c2]-sum[r1][c2]-sum[r2][c1]

        return result

C

C

JavaScript

Ruby

Swift

Go

Scala

Kotlin

Rust

PHP