Matrix area sum of LeetCode dynamic programming

Get into the habit of writing together! This is the 4th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

topic

matrix area and

Given a  m x n matrix  mat and an integer k, return a matrix  answer where each  answer[i][j] is the sum of all elements that satisfy the following conditions  mat[r][c]

i - k <= r <= i + k,
j - k <= c <= j + kand
(r, c) in the matrix.  

Example 1:

输入:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
输出:[[12,21,16],[27,45,33],[24,39,28]]
复制代码

Example 2:

输入:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
输出:[[45,45,45],[45,45,45],[45,45,45]]
复制代码

hint:

m == mat.length
n == mat[i].length
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100
复制代码

answer

problem-solving analysis

Problem solving ideas

  1. This problem is a typical dynamic programming problem;
  2. dp[i][j] represents the maximum square side length that can be formed by the lower right corner of the i-th row and the j-th column, then the recursion formula is:
dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]);
复制代码

Then max * maxget the maximum value of the rectangular area by .
3. The problem-solving code is as follows:
Complexity
Time Complexity: O(M * N)
Space Complexity:O(M * N)

problem solving code

The solution code is as follows (detailed comments in the code):

class Solution {
    public int maximalSquare(char[][] matrix) {
        /**
        dp[i][j]表示以第i行第j列为右下角所能构成的最大正方形边长, 则递推式为: 
        dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]);
        **/
        int m = matrix.length;
        if(m < 1) return 0;
        int n = matrix[0].length;
        int max = 0;
        int[][] dp = new int[m+1][n+1];
        
        for(int i = 1; i <= m; ++i) {
            for(int j = 1; j <= n; ++j) {
                if(matrix[i-1][j-1] == '1') {
                    dp[i][j] = 1 + Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1]));
                    max = Math.max(max, dp[i][j]); 
                }
            }
        }
        
        return max*max;
    }
}
复制代码

Feedback results after submission (because this topic has not been optimized, the performance is average):

image.png

Reference Information

Guess you like

Origin juejin.im/post/7083104853047640094